@gjermundgaraba/clankerauth-dev 0.26.2 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.txt +12 -219
- package/dist/{access-CoaNEa0I.mjs → access-CGVwFSPz.mjs} +1 -1
- package/dist/{dist-Dse7wyrJ.mjs → dist-BwJIqVtn.mjs} +1 -1
- package/dist/dist-CLLAHXOK.mjs +17 -0
- package/dist/{factory-tEOeUNZI.mjs → factory-Cf28yuX6.mjs} +3 -3
- package/dist/{get-id-field-CHlYHt3y.mjs → get-id-field-DvYh1rwM.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/kysely-adapter-B9j0_OfU.mjs +1 -0
- package/dist/{organization-FxrB4RLj.mjs → organization-B_0UJJOj.mjs} +1 -1
- package/dist/{schema-check-6AE7KkNs.mjs → schema-check-DYtufmXq.mjs} +1 -1
- package/dist/{schemas-CYWNDEcx.mjs → schemas-lRZfTY17.mjs} +1 -1
- package/dist/src-dv9-ePIU.mjs +539 -0
- package/dist/web/assets/index-C-vB7TuL.css +1 -0
- package/dist/web/assets/index-C_9T06d-.js +2300 -0
- package/dist/web/index.html +2 -2
- package/package.json +4 -4
- package/dist/dist-BtO0lgmD.mjs +0 -17
- package/dist/kysely-adapter-BxenTacV.mjs +0 -1
- package/dist/src-mhYy55vF.mjs +0 -539
- package/dist/web/assets/index-kuPpbPut.js +0 -2300
- package/dist/web/assets/index-sZpVl70Z.css +0 -1
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
import{t as e}from"./esm-CdWTLqG7.mjs";import{c as t,r as n,s as r}from"./sqlite-introspector-DSCAP82F-CISODKY3.mjs";import{c as i,i as a,n as o,o as s,r as c,s as l,t as u}from"./dist-CLLAHXOK.mjs";import{t as d}from"./compiled-query-C8AL3JwF.mjs";import{A as f,B as p,C as m,D as h,E as g,G as _,H as v,I as y,J as b,K as x,L as S,M as ee,N as C,O as te,P as w,R as ne,S as T,T as re,U as ie,V as ae,W as oe,X as se,Y as ce,_ as le,a as ue,b as de,d as fe,f as pe,g as me,h as he,i as ge,k as _e,l as ve,m as ye,o as be,p as xe,q as Se,s as Ce,t as we,u as eee,v as Te,w as Ee,x as De,y as Oe,z as tee}from"./get-id-field-DvYh1rwM.mjs";import{A as ke,C as Ae,D as je,E as Me,F as Ne,I as Pe,L as Fe,M as E,N as D,O as Ie,P as O,S as k,T as nee,_ as Le,a as Re,b as ze,c as Be,d as Ve,f as He,g as Ue,h as We,i as Ge,j as Ke,k as qe,l as Je,m as Ye,n as Xe,o as Ze,p as Qe,r as $e,s as et,t as tt,u as nt,v as A,w as rt,x as it,y as at}from"./schemas-lRZfTY17.mjs";import{a as ot,c as ree,l as iee,o as aee,r as oee,s as see}from"./schema-check-DYtufmXq.mjs";import{n as cee,r as lee}from"./factory-Cf28yuX6.mjs";import{n as uee}from"./access-CGVwFSPz.mjs";import*as st from"node:crypto";import{randomBytes as ct,scrypt as lt}from"node:crypto";import*as ut from"node:path";import dt,{dirname as ft,join as pt,resolve as mt}from"node:path";import*as ht from"node:url";import{fileURLToPath as gt}from"node:url";import _t,*as vt from"node:os";import*as yt from"node:child_process";import{Duplex as bt,PassThrough as xt,Readable as St,pipeline as Ct}from"node:stream";import{IncomingMessage as wt,createServer as dee}from"node:http";import{isIP as Tt}from"node:net";import*as Et from"node:fs";import Dt,{mkdirSync as fee}from"node:fs";import{request as pee}from"node:https";import*as mee from"node:stream/promises";import{pipeline as hee}from"node:stream/promises";import*as Ot from"node:zlib";import*as kt from"node:readline";import{DatabaseSync as gee}from"node:sqlite";import At from"node:fs/promises";import{lookup as _ee}from"node:dns/promises";const jt=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}},Mt={pipe(){return jt(this,arguments)}},Nt=/*#__PURE__*/ function(){function e(){}return e.prototype=Mt,e}(),j=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},M=e=>e,Pt=e=>()=>e,Ft=/*#__PURE__*/ Pt(!0),It=/*#__PURE__*/ Pt(!1),Lt=/*#__PURE__*/ Pt(void 0),Rt=Lt;function zt(e,...t){return jt(e,t)}function Bt(e,t,n,r,i,a,o,s,c){switch(arguments.length){case 1:return e;case 2:return function(){return t(e.apply(this,arguments))};case 3:return function(){return n(t(e.apply(this,arguments)))};case 4:return function(){return r(n(t(e.apply(this,arguments))))};case 5:return function(){return i(r(n(t(e.apply(this,arguments)))))};case 6:return function(){return a(i(r(n(t(e.apply(this,arguments))))))};case 7:return function(){return o(a(i(r(n(t(e.apply(this,arguments)))))))};case 8:return function(){return s(o(a(i(r(n(t(e.apply(this,arguments))))))))};case 9:return function(){return c(s(o(a(i(r(n(t(e.apply(this,arguments)))))))))}}}function Vt(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function Ht(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i!==n&&t.set(i,i),i}}const Ut=e=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;e instanceof Error&&t.delete(`stack`);let n=Object.getPrototypeOf(e),r=n;for(;r!==null&&r!==Object.prototype;){let e=Reflect.ownKeys(r);for(let n=0;n<e.length;n++)t.add(e[n]);r=Object.getPrototypeOf(r)}return t.has(`constructor`)&&typeof e.constructor==`function`&&n===e.constructor.prototype&&t.delete(`constructor`),t},Wt=/*#__PURE__*/ new WeakSet,Gt=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let Kt=0;const qt=()=>{Kt++};function Jt(e){return typeof e==`string`}function Yt(e){return typeof e==`number`}function Xt(e){return typeof e==`boolean`}function Zt(e){return typeof e==`symbol`}function Qt(e){return Jt(e)||Yt(e)||Zt(e)}function $t(e){return typeof e==`function`}function en(e){return e===void 0}function tn(e){return e!==void 0}function nn(e){return e!==null}function rn(e){return e==null}function vee(e){return e!=null}function yee(e){return!1}function an(e){return!0}function on(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sn(e){return on(e)}function cn(e){return typeof e==`object`&&!!e||$t(e)}const N=/*#__PURE__*/ j(2,(e,t)=>cn(e)&&t in e),ln=/*#__PURE__*/ j(2,(e,t)=>N(e,`_tag`)&&e._tag===t);function bee(e){return e instanceof Error}function xee(e){return N(e,Symbol.iterator)||Jt(e)}const un=`~effect/Hash`,dn=e=>{switch(typeof e){case`number`:return _n(e);case`bigint`:return vn(e.toString(10));case`string`:return vn(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?vn(`Invalid Date`):vn(e.toISOString());if(e instanceof RegExp)return vn(e.toString());{if(Wt.has(e))return fn(e);let t=Dn.get(e);if(t!==void 0)return t;if(On.has(e))return qt(),vn(`[Circular]`);On.add(e);let n=Kt,r;try{r=`~effect/Hash`in e?e[un]():typeof e==`function`?fn(e):e instanceof DataView?Sn(Gt(e)):Array.isArray(e)||ArrayBuffer.isView(e)?Sn(e):e instanceof Map?Cn(e):e instanceof Set?Tn(e):bn(e)}finally{On.delete(e)}return n===Kt&&Dn.set(e,r),r}}return hn(pn(vn(String(e))))},fn=e=>(En.has(e)||En.set(e,hn(Math.random()*4294967296|0)),En.get(e)),pn=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),mn=/*#__PURE__*/ j(2,(e,t)=>pn(Math.imul(e,2654435761)+Math.imul(t,2246822507))),hn=e=>e&3221225471|e>>>1&1073741824,gn=/*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)),_n=e=>{let t=e|0;return t===e?hn(t):(gn.setFloat64(0,e===e?e:NaN),hn(mn(gn.getInt32(0),gn.getInt32(4))))},vn=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return hn(t)},yn=(e,t)=>{let n=12289;for(let r of t)n^=mn(dn(r),dn(e[r]));return hn(n)},bn=e=>yn(e,Ut(e)),xn=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return hn(r)},Sn=e=>{let t=6151;for(let n of e)t=mn(t,dn(n));return hn(t)},Cn=/*#__PURE__*/ xn(/*#__PURE__*/ vn(`Map`),([e,t])=>mn(dn(e),dn(t))),wn=/*#__PURE__*/ vn(`Set`),Tn=/*#__PURE__*/ xn(wn,e=>mn(wn,dn(e))),En=/*#__PURE__*/ new WeakMap,Dn=/*#__PURE__*/ new WeakMap,On=/*#__PURE__*/ new WeakSet,kn=`~effect/Equal`;function An(){return arguments.length===1?e=>jn(e,arguments[0]):jn(arguments[0],arguments[1])}function jn(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||Wt.has(e)||Wt.has(t)?!1:Mn(e,t):!1}function Mn(e,t){let n=Pn.length;for(let r=n;r-->0;)if(Pn[r]===e&&Fn[r]===t)return!0;if(n)return Nn(e,t);let r=In.get(e);r||In.set(e,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Nn(e,t)),i}function Nn(e,t){Pn.push(e),Fn.push(t);try{return Ln(e,t)}finally{Pn.pop(),Fn.pop()}}const Pn=[],Fn=[],In=/*#__PURE__*/ new WeakMap;function Ln(e,t){if(dn(e)!==dn(t))return!1;if(e instanceof Date){if(!(t instanceof Date))return!1;let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=Vn(e);if(n!==Vn(t)||typeof e==`function`&&!n)return!1;if(n)return e[kn](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Rn(e,t);if(ArrayBuffer.isView(e)){let n=e instanceof DataView;return!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||n!==t instanceof DataView?!1:n?zn(Gt(e),Gt(t)):zn(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:Bn(e,t,Cee,wee):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:Bn(e,t,dn,jn):See(e,t)}function Rn(e,t){for(let n=0;n<e.length;n++)if(!jn(e[n],t[n]))return!1;return!0}function zn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function See(e,t){let n=Ut(e),r=Ut(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!jn(e[i],t[i]))return!1;return!0}function Bn(e,t,n,r){let i=/* @__PURE__ */ new Map,a=0;for(let e of t){let t=n(e),r=i.get(t);r?r.push(e):i.set(t,[e]),a++}outer:for(let t of e){let e=i.get(n(t));if(e){for(let n=0;n<e.length;n++)if(r(t,e[n])){e[n]=e[e.length-1],e.pop(),a--;continue outer}}return!1}return a===0}const Cee=e=>dn(e[0]),wee=(e,t)=>jn(e[0],t[0])&&jn(e[1],t[1]),Vn=e=>N(e,kn),Tee=()=>An,Hn=/*#__PURE__*/ Symbol.for(`~effect/Redactable`),Eee=e=>N(e,Hn);function Un(e){return Eee(e)?Wn(e):e}function Wn(e){return e[Hn](globalThis[`~effect/Fiber/currentFiber`]?.context??Dee)}const Gn=`~effect/Fiber/currentFiber`,Kn=/*#__PURE__*/ new Map,Dee={"~effect/Context":{},base:Kn,depth:0,mapUnsafe:Kn,pipe(){return jt(this,arguments)}};function qn(e,t){let n=t?.space??0,r=/* @__PURE__ */ new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,t=0){try{return l(e,t)}catch{return(typeof e==`object`&&e||typeof e==`function`)&&r.delete(e),`[inspection threw]`}}function l(e,n=0){if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return Oee;r.add(e);let l;if(Hn in e)l=c(Wn(e),n);else if(Array.isArray(e))l=!i||e.length<=1?`[${e.map(e=>c(e,n)).join(`,`)}]`:`[\n${a(n+1)}${e.map(e=>c(e,n+1)).join(`,
|
|
2
|
+
`+a(n+1))}\n${a(n)}]`;else if(e instanceof Date)l=kee(e);else if(!t?.ignoreToString&&N(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Aee(e);l=e instanceof Error&&e.cause!==void 0?`${t} (cause: ${c(e.cause,n)})`:t}else if(Symbol.iterator in e)l=`${e.constructor.name}(${c(Array.from(e),n)})`;else{let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${Jn(t)}:${c(Xn(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Jn(t)}: ${c(Xn(e,t),n+1)}`).join(`,
|
|
3
|
+
`)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}const Oee=`[Circular]`;function Jn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function Yn(e){return e.map(e=>`[${Jn(e)}]`).join(``)}function kee(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Aee(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function Xn(e,t){try{return e[t]}catch{return`[property access threw]`}}function Zn(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=N(r,Hn)?Un(r):Un(t);if(typeof i==`bigint`)return qn(i);if(typeof i!=`object`||!i)return i;let a=i instanceof Error&&!N(i,`toJSON`)?{...i,name:i.name,message:i.message}:i;for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return;if(n.push(i),a!==i&&n.push(a),!jee(a)||Mee(a))return a;let o=new Proxy(a,{get(e,t){let n=Reflect.get(e,t,e);return Object.getOwnPropertyDescriptor(e,t)?.get===void 0?n:Un(n)}});return n.push(o),o},t?.space)??`null`}function jee(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function Mee(e){for(let t of[Number.prototype.valueOf,Boolean.prototype.valueOf,String.prototype.valueOf])try{return Reflect.apply(t,e,[]),!0}catch{}return!1}const Qn=/*#__PURE__*/ Symbol.for(`nodejs.util.inspect.custom`),$n=e=>{try{return e=Un(e),N(e,`toJSON`)&&$t(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map($n):e}catch{return`[toJSON threw]`}},Nee=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Zn(e,{space:t}):qn(e,{space:t})}catch{return String(e)}},er={toJSON(){return $n(this)},[Qn](){return this.toJSON()},toString(){return qn(this.toJSON())}};var tr=class{[Qn](){return this.toJSON()}toString(){return qn(this.toJSON())}};const Pee=/*#__PURE__*/ (()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),nr=()=>Error.stackTraceLimit,rr=e=>{Pee&&(Error.stackTraceLimit=e)};var ir=class{constructor(e){this.value=e,this.done=!1}next(e){return this.done?(this.value=e,this):(this.done=!0,{value:this.value,done:!1})}};const ar=/*#__PURE__*/ (()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=nr();if(r===0)return n[e];rr(2);let i=t[e](()=>/* @__PURE__ */ Error());return rr(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function or(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function sr(e,t){for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&or(e,n,t[n])}const cr=`~effect/Effect`,lr=`~effect/Exit`,ur={_A:M,_E:M,_R:M},dr=`${cr}/identifier`,fr=`${cr}/args`,pr=`${cr}/evaluate`,mr=`${cr}/successCont`,hr=`${cr}/failureCont`,gr=`${cr}/ensureCont`,_r=/*#__PURE__*/ Symbol.for(`effect/Effect/Yield`),vr={pipe(){return jt(this,arguments)},toJSON(){return{...this}},toString(){return qn(this.toJSON(),{ignoreToString:!0,space:2})},[Qn](){return this.toJSON()}},yr={[cr]:ur,...vr,[Symbol.iterator](){return new ir(this)},toJSON(){return{_id:`Effect`,op:this[dr],...`~effect/Effect/args`in this?{args:this[fr]}:void 0}}},br=e=>N(e,cr),xr=e=>N(e,lr),Sr=`~effect/Cause`,Cr=`~effect/Cause/Reason`,wr=e=>N(e,Sr),Tr=e=>N(e,Cr);var Er=class{constructor(e){this[Sr]=Sr,this.reasons=e}pipe(){return jt(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${qn(this.reasons)})`}[Qn](){return this.toJSON()}[kn](e){return wr(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>An(t,e.reasons[n]))}[un](){return Sn(this.reasons)}};const Dr=/*#__PURE__*/ new WeakMap;var Or=class{[Cr];annotations;_tag;constructor(e,t,n){if(this[Cr]=Cr,this._tag=e,t!==kr&&typeof n==`object`&&n&&t.size>0){let e=Dr.get(n);e&&(t=new Map([...e,...t])),Dr.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return jt(this,arguments)}toString(){return qn(this)}[Qn](){return this.toString()}};const kr=/*#__PURE__*/ new Map;var Ar=class extends Or{constructor(e,t=kr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${qn(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[kn](e){return zr(e)&&An(this.error,e.error)&&An(this.annotations,e.annotations)}[un](){return mn(vn(this._tag))(mn(dn(this.error))(dn(this.annotations)))}};const jr=e=>new Er(e),Mr=(e,t)=>{let n=/* @__PURE__ */ new Map,r=[];for(let i of e.concat(t)){let e=dn(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>An(e,i)))continue;else t.push(i);r.push(i)}return r},Nr=/*#__PURE__*/ j(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new Er(Mr(e.reasons,t.reasons));return An(e,n)?e:n}),Pr=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)Vr(e)&&!n.some(t=>Vr(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new Er(n)},Fee=/*#__PURE__*/ new Er([]),Fr=e=>new Er([new Ar(e)]);var Ir=class extends Or{constructor(e,t=kr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${qn(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[kn](e){return Br(e)&&An(this.defect,e.defect)&&An(this.annotations,e.annotations)}[un](){return mn(vn(this._tag))(mn(dn(this.defect))(dn(this.annotations)))}};const Lr=e=>new Er([new Ir(e)]),Rr=/*#__PURE__*/ j(e=>wr(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new Er(e.reasons.map(e=>e.annotate(t,n)))),zr=e=>e._tag===`Fail`,Br=e=>e._tag===`Die`,Vr=e=>e._tag===`Interrupt`;function Iee(e){return Xr(`Effect.evaluate: Not implemented`)}const Hr=e=>({...yr,[dr]:e.op,[pr]:e[`~effect/Effect/evaluate`]??Iee,[mr]:e[mr],[hr]:e[hr],[gr]:e[gr]}),Ur=e=>{let t=Hr(e),n=function(e){this[fr]=e};return n.prototype=t,function(e){return new n(e)}},Wr=e=>{let t={[lr]:lr,_tag:e.op,get[e.prop](){return this[fr]},...Hr(e),toString(){return`${e.op}(${qn(this[fr])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[fr]}},[kn](e){return xr(e)&&e._tag===this._tag&&An(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[un](){return mn(vn(e.op),dn(this[fr]))}},n=function(e){this[fr]=e};return n.prototype=t,function(e){return new n(e)}},Gr=/*#__PURE__*/ Wr({op:`Success`,prop:`value`,[pr](e){let t=e.getCont(mr);return t?t[mr](this[fr],e,this):e.yieldWith(this)}}),Kr={key:`effect/Cause/StackTrace`},qr={key:`effect/Cause/InterruptorStackTrace`},Jr=/*#__PURE__*/ Wr({op:`Failure`,prop:`cause`,[pr](e){let t=this[fr],n=!1;e.cache.stackFrame&&(t=Rr(t,{mapUnsafe:/* @__PURE__ */ new Map([[Kr.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(hr),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=dr in r,r=e.getCont(hr);a&&(t=jr(t.reasons.filter(e=>e._tag!==`Fail`))),t=Pr(t,i),n=!0}return r?r[hr](t,e,n?void 0:this):e.yieldWith(n?Jr(t):this)}}),Yr=e=>Jr(Fr(e)),Xr=e=>Jr(Lr(e)),Zr=/*#__PURE__*/ Ur({op:`WithFiber`,[pr](e){return this[fr](e)}}),Lee=/*#__PURE__*/ function(){class e extends globalThis.Error{}let t=/*#__PURE__*/ Hr({op:`YieldableError`,[pr](){return Yr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Qr=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Symbol.for(`effect/Data/Error/plainArgs`);return class extends Lee{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(sr(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),$r=e=>{class t extends Qr{_tag=e}return t.prototype.name=e,t},ei=`~effect/Cause/NoSuchElementError`,Ree=e=>N(e,ei);var zee=class extends (/*#__PURE__*/ $r(`NoSuchElementError`)){[ei]=ei;constructor(e){super({message:e})}};const ti=`~effect/Cause/Done`,Bee=e=>N(e,ti),ni={[ti]:ti,_tag:`Done`,value:void 0},ri=e=>e===void 0?ni:{[ti]:ti,_tag:`Done`,value:e},Vee=/*#__PURE__*/ Yr(ni),Hee=e=>e===void 0?Vee:Yr(ri(e)),ii=e=>Hr({op:e.label,[pr]:e.evaluate}),ai=e=>(t,n)=>t===n||e(t,n),Uee=(e,t)=>e===t,oi=()=>Uee;function Wee(e){return ai((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e[r](t[r],n[r]))return!1;return!0})}function Gee(e){return ai((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0})}const si=`~effect/Option`,ci={[si]:{_A:e=>e},...vr,[Symbol.iterator](){return new ir(this)}},Kee=/*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(ci),{_tag:`Some`,_op:`Some`,[kn](e){return li(e)&&di(e)&&An(this.value,e.value)},[un](){return mn(dn(this._tag))(dn(this.value))},toString(){return`some(${qn(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:$n(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),qee=/*#__PURE__*/ dn(`None`),Jee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(ci),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[kn](e){return li(e)&&ui(e)},[un](){return qee},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),li=e=>N(e,si),ui=e=>e._tag===`None`,di=e=>e._tag===`Some`,Yee=/*#__PURE__*/ Object.create(Jee),fi=function(e){this.value=e};fi.prototype=Kee;const Xee=e=>new fi(e),pi=`~effect/Result`,mi={[pi]:{
|
|
4
|
+
/* v8 ignore next 2 */
|
|
5
|
+
_A:e=>e,_E:e=>e},...vr,[Symbol.iterator](){return new ir(this)}},Zee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(mi),{_tag:`Success`,_op:`Success`,[kn](e){return hi(e)&&_i(e)&&An(this.success,e.success)},[un](){return mn(dn(this._tag))(dn(this.success))},toString(){return`success(${qn(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:$n(this.success)}}}),Qee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(mi),{_tag:`Failure`,_op:`Failure`,[kn](e){return hi(e)&&gi(e)&&An(this.failure,e.failure)},[un](){return mn(dn(this._tag))(dn(this.failure))},toString(){return`failure(${qn(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:$n(this.failure)}}}),hi=e=>N(e,pi),gi=e=>e._tag===`Failure`,_i=e=>e._tag===`Success`,vi=function(e){this.failure=e};vi.prototype=Qee;const yi=e=>new vi(e),bi=function(e){this.success=e};bi.prototype=Zee;const xi=e=>new bi(e);function Si(e){return(t,n)=>t===n?0:e(t,n)}const Ci=/*#__PURE__*/ Si((e,t)=>e<t?-1:1),wi=/*#__PURE__*/ Si((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e<t?-1:1),Ti=/*#__PURE__*/ j(2,(e,t)=>Si((n,r)=>e(t(n),t(r)))),Ei=e=>j(2,(t,n)=>e(t,n)===-1),Di=e=>j(2,(t,n)=>e(t,n)===1),Oi=e=>j(2,(t,n)=>e(t,n)!==1),ki=e=>j(2,(t,n)=>e(t,n)!==-1),Ai=()=>Yee,ji=Xee,Mi=ui,Ni=di,Pi=/*#__PURE__*/ j(2,(e,{onNone:t,onSome:n})=>Mi(e)?t():n(e.value)),Fi=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?t():e.value),Ii=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?t():e),Li=e=>e==null?Ai():ji(e),Ri=e=>e===void 0?Ai():ji(e),zi=/*#__PURE__*/ Fi(Lt),Bi=e=>(...t)=>{try{return ji(e(...t))}catch{return Ai()}},Vi=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?Ai():ji(t(e.value))),Hi=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?Ai():t(e.value)),Ui=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?Ai():t(e.value)?ji(e.value):Ai()),Wi=`~effect/Context/Service`,P=function(){function e(){}let t=e;Object.setPrototypeOf(t,Gi);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[qi]=qi,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&Ki.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Gi={[Wi]:Wi,.../*#__PURE__*/ ii({label:`Service`,evaluate(e){return Gr(da(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return aa(this,e)},use(e){return Zr(t=>e(da(t.context,this)))},useSync(e){return Zr(t=>Gr(e(da(t.context,this))))}},Ki=/*#__PURE__*/ new Set,qi=`~effect/Context/Reference`,Ji=`~effect/Context`,Yi=(e,t,n,r)=>{let i=Object.create($ee);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Xi=(e,t)=>{t&&(Xi(e,t.parent),e.set(t.key,t.value))},Zi=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Xi(t,e.overlay),e._flat=t},Qi=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),ta(n)},$i=/*#__PURE__*/ Symbol(),ea=(e,t)=>{let n=e;for(let e=n.overlay;e;e=e.parent)if(e.key===t)return e.value;let r=n.base.get(t);return r===void 0&&!n.base.has(t)?$i:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=8&&(n.base=Zi(n),n.overlay=void 0,n.depth=0),r)},ta=e=>Yi(void 0,e,void 0,0),$ee={get mapUnsafe(){return Zi(this)},...vr,[Ji]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[kn](e){if(!na(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!An(r,n.get(e)))return!1;return!0},[un](){return _n(this.mapUnsafe.size)}},ete=(e,t)=>e.cacheRoot===t.cacheRoot,na=e=>N(e,Ji),tte=e=>N(e,Wi),ra=e=>!!e[qi],ia=()=>nte,nte=/*#__PURE__*/ ta(/*#__PURE__*/ new Map),aa=(e,t)=>ta(/* @__PURE__ */ new Map([[e.key,t]])),oa=/*#__PURE__*/ j(3,(e,t,n)=>rte(e,t.key,n)),rte=(e,t,n)=>{let r=e,i=Ki.has(t)?void 0:r.cacheRoot;if(r.depth>=8){let e=new Map(r._flat??r.base);return r._flat||Xi(e,r.overlay),e.set(t,n),Yi(i,e,void 0,0)}return Yi(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},sa=/*#__PURE__*/ j(3,(e,t,n)=>{let r=ea(e,t.key);return r===$i?ra(t)?pa(t):n():r}),ca=/*#__PURE__*/ j(2,(e,t)=>la(e,t.key)),la=(e,t)=>{let n=ea(e,t);return n===$i?void 0:n},ua=/*#__PURE__*/ j(2,(e,t)=>{let n=ea(e,t.key);if(n===$i){if(ra(t))return pa(t);throw ite(t)}return n}),da=ua,fa=`~effect/Context/defaultValue`,pa=e=>fa in e?e[fa]:e[fa]=e.defaultValue(),ite=e=>{let t=/* @__PURE__ */ Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
|
|
6
|
+
`);e.splice(1,3),t.stack=e.join(`
|
|
7
|
+
`)}return t},ma=/*#__PURE__*/ j(2,(e,t)=>{let n=ea(e,t.key);return n===$i?ra(t)?ji(pa(t)):Ai():ji(n)}),ha=/*#__PURE__*/ j(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:Qi(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),ate=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return ta(t)},ga=(...e)=>t=>Qi(t,t=>{for(let n=0;n<e.length;n++)t.delete(e[n].key)}),_a=P,va=e=>e.length>0,ya=e=>e>0?Math.floor(e):0,ba=xi,xa=yi,ote=e=>{if($t(e))try{return ba(e())}catch(e){return xa(e)}try{return ba(e.try())}catch(t){return xa(e.catch(t))}},Sa=hi,Ca=gi,wa=_i,ste=/*#__PURE__*/ j(2,(e,t)=>Ca(e)?xa(t(e.failure)):e),Ta=/*#__PURE__*/ j(2,(e,t)=>wa(e)?ba(t(e.success)):e),cte=/*#__PURE__*/ j(2,(e,{onFailure:t,onSuccess:n})=>Ca(e)?t(e.failure):n(e.success)),lte=/*#__PURE__*/ (/* @__PURE__ */ j(2,(e,t)=>Ca(e)?t(e.failure):e.success))(Lt),ute=Wee,dte=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},fte=()=>({}),pte=e=>Object.keys(e).length===0,mte=/*#__PURE__*/ j(2,(e,t)=>Object.hasOwn(e,t)),Ea=/*#__PURE__*/ j(2,(e,t)=>{let n={...e};for(let r of Da(e))or(n,r,t(e[r],r));return n}),hte=/*#__PURE__*/ j(2,(e,t)=>{let n=fte();for(let r of Da(e))t(e[r],r)&&or(n,r,e[r]);return n}),Da=e=>Object.keys(e),gte=/*#__PURE__*/ j(3,(e,t,n)=>({...e,[t]:n})),_te=e=>j(2,(t,n)=>{for(let r of Da(t))if(!mte(n,r)||!e(t[r],n[r]))return!1;return!0}),vte=e=>{let t=_te(e);return(e,n)=>t(e,n)&&t(n,e)},Oa=globalThis.Array,ka=e=>Oa.isArray(e)?e:Oa.from(e),Aa=e=>Oa.isArray(e)?e:[e],ja=/*#__PURE__*/ j(2,(e,t)=>[...e,t]);Oa.isArray;const Ma=va,Na=va;function yte(e){let t=Number(e);return String(t)===e&&Number.isInteger(t)&&t>=0&&t<2**32-1}const bte=(e,t)=>Math.min(ya(e),t),xte=/*#__PURE__*/ j(2,(e,t)=>{let n=ka(e);return n.slice(0,bte(t,n.length))}),Ste=e=>Oa.from(e).reverse(),Cte=(e,t)=>{let n=dn(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(An(e,t))return!1;return r.push(t),!0},Pa=()=>[],Fa=e=>[e],Ia=/*#__PURE__*/ j(2,(e,t)=>e.map(t)),wte=Gee,Tte=e=>{let t=ka(e);if(t.length<2)return[...t];let n=/* @__PURE__ */ new Map,r=[];for(let e of t)Cte(n,e)&&r.push(e);return r},La=`~effect/Duration`,Ra=/*#__PURE__*/ BigInt(0),za=/*#__PURE__*/ BigInt(1),Ete=/*#__PURE__*/ BigInt(2),Dte=/*#__PURE__*/ BigInt(10),Ba=/*#__PURE__*/ BigInt(24),Va=/*#__PURE__*/ BigInt(60),Ha=/*#__PURE__*/ BigInt(1e3),Ua=/*#__PURE__*/ BigInt(1e6),Wa=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),Ga=e=>Number.isInteger(e)?BigInt(e)*Ua:Wa(e*1e6),Ka=e=>eo(Number.isFinite(e)?Wa(e):e),qa=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=Dte**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return Ote(r?-o:o,a)},Ote=(e,t)=>{let n=e<Ra?-e:e,r=n/t+(n%t*Ete>=t?za:Ra);return e<Ra?-r:r},kte=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Ja=e=>{switch(typeof e){case`number`:return uo(e);case`bigint`:return lo(e);case`string`:{if(e===`Infinity`)return so;if(e===`-Infinity`)return co;let t=kte.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return lo(qa(r,za));if(i===`micro`||i===`micros`)return lo(qa(r,Ha));let a=Number(r);switch(i){case`milli`:case`millis`:return uo(a);case`second`:case`seconds`:return fo(a);case`minute`:case`minutes`:return po(a);case`hour`:case`hours`:return mo(a);case`day`:case`days`:return ho(a);case`week`:case`weeks`:return go(a)}break}case`object`:{if(e===null)break;if(La in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(Yt)?Ya(e):Number.isNaN(e[0])||Number.isNaN(e[1])?oo:e[0]===-1/0||e[1]===-1/0?co:e[0]===1/0||e[1]===1/0?so:Ka(e[0]*1e9+e[1]);let t=e,n=0;return t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds?eo(n):Ka(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0))}}return Ya(e)},Ya=e=>{throw Error(`Invalid Input: ${e}`)},Xa={_tag:`Millis`,millis:0},Za={_tag:`Infinity`},Qa={_tag:`NegativeInfinity`},$a={[La]:La,[un](){switch(this.value._tag){case`Millis`:return dn(Ga(this.value.millis));case`Nanos`:return dn(this.value.nanos);default:return bn(this.value)}},[kn](e){return to(e)&&Co(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[Qn](){return this.toJSON()},pipe(){return jt(this,arguments)}},eo=e=>{let t=Object.create($a);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Xa:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Ga(e)}:e>0?Za:Qa:e===Ra?Xa:{_tag:`Nanos`,nanos:e},t},to=e=>N(e,La),no=e=>e.value._tag!==`Infinity`&&e.value._tag!==`NegativeInfinity`,ro=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===Ra;case`Infinity`:case`NegativeInfinity`:return!1}},io=e=>{switch(e.value._tag){case`Millis`:return e.value.millis<0;case`Nanos`:return e.value.nanos<Ra;case`NegativeInfinity`:return!0;case`Infinity`:return!1}},ao=e=>{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:return so;case`Millis`:return e.value.millis<0?eo(-e.value.millis):e;case`Nanos`:return e.value.nanos<Ra?eo(-e.value.nanos):e}},oo=/*#__PURE__*/ eo(0),so=/*#__PURE__*/ eo(1/0),co=/*#__PURE__*/ eo(-1/0),lo=e=>eo(e),uo=e=>eo(e),fo=e=>eo(e*1e3),po=e=>eo(e*6e4),mo=e=>eo(e*36e5),ho=e=>eo(e*864e5),go=e=>eo(e*6048e5),_o=e=>bo(Ja(e),{onMillis:M,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),vo=e=>bo(Ja(e),{onMillis:e=>e/1e3,onNanos:e=>Number(e)/1e9,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),yo=e=>{let t=Ja(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return Ga(t.value.millis)}},bo=/*#__PURE__*/ j(2,(e,t)=>{switch(e.value._tag){case`Millis`:return t.onMillis(e.value.millis);case`Nanos`:return t.onNanos(e.value.nanos);case`Infinity`:return t.onInfinity();case`NegativeInfinity`:return(t.onNegativeInfinity??t.onInfinity)()}}),xo=/*#__PURE__*/ j(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(yo(e),t.value.nanos):n.onNanos(e.value.nanos,yo(t))),So=(e,t)=>xo(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Co=/*#__PURE__*/ j(2,(e,t)=>So(e,t)),wo=e=>{if(e.value._tag===`Infinity`)return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};if(e.value._tag===`NegativeInfinity`)return{days:-1/0,hours:-1/0,minutes:-1/0,seconds:-1/0,millis:-1/0,nanos:-1/0};let t=yo(e),n=t<Ra,r=n?-t:t,i=r/Ua,a=i/Ha,o=a/Va,s=o/Va,c=s/Ba,l=n?-1:1;return{days:l*Number(c),hours:l*Number(s%Ba),minutes:l*Number(o%Va),seconds:l*Number(a%Va),millis:l*Number(i%Ha),nanos:l*Number(r%Ua)}},To=e=>{if(e.value._tag===`Infinity`)return`Infinity`;if(e.value._tag===`NegativeInfinity`)return`-Infinity`;if(ro(e))return`0`;if(io(e))return`-`+To(ao(e));let t=wo(e),n=[];return t.days!==0&&n.push(`${t.days}d`),t.hours!==0&&n.push(`${t.hours}h`),t.minutes!==0&&n.push(`${t.minutes}m`),t.seconds!==0&&n.push(`${t.seconds}s`),t.millis!==0&&n.push(`${t.millis}ms`),t.nanos!==0&&n.push(`${t.nanos}ns`),n.join(` `)},Eo=/*#__PURE__*/ _a(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new jo}),Do=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Oo=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ko=e=>{try{return Oo(e)}catch{return Do(e)}};var Ao=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},jo=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?Do:ko)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new Mo(this.setImmediate)}},Mo=class{tasks=/*#__PURE__*/ new Ao;running=void 0;setImmediate;constructor(e=ko){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}};const No=/*#__PURE__*/ _a(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Po=/*#__PURE__*/ _a(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),Fo=class extends Nt{constructor(e){super(),e&&sr(this,e)}},Io=e=>class extends Fo{_tag=e},Lo=()=>new Proxy({},{get(e,t,n){return t===`$is`?ln:t===`$match`?Ro:e=>({...e,_tag:t})}});function Ro(){if(arguments.length===1){let e=arguments[0];return function(t){return e[t._tag](t)}}let e=arguments[0];return arguments[1][e._tag](e)}const zo=Qr,Bo=$r,Vo=`~effect/encoding/EncodingError`;var Ho=class extends (/*#__PURE__*/ Bo(`EncodingError`)){[Vo]=Vo};const Uo=e=>{switch(e){case 16:return qo();case 32:return Jo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Ko();return t}}},Wo=/*#__PURE__*/ Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),Go=()=>Math.random()*4294967296>>>0,Ko=()=>{let e=Go();return String.fromCharCode(Wo[e>>>28],Wo[e>>>24&15],Wo[e>>>20&15],Wo[e>>>16&15],Wo[e>>>12&15],Wo[e>>>8&15],Wo[e>>>4&15],Wo[e&15])},qo=()=>{let e=Go(),t=Go();return String.fromCharCode(Wo[e>>>28],Wo[e>>>24&15],Wo[e>>>20&15],Wo[e>>>16&15],Wo[e>>>12&15],Wo[e>>>8&15],Wo[e>>>4&15],Wo[e&15],Wo[t>>>28],Wo[t>>>24&15],Wo[t>>>20&15],Wo[t>>>16&15],Wo[t>>>12&15],Wo[t>>>8&15],Wo[t>>>4&15],Wo[t&15])},Jo=()=>{let e=Go(),t=Go(),n=Go(),r=Go();return String.fromCharCode(Wo[e>>>28],Wo[e>>>24&15],Wo[e>>>20&15],Wo[e>>>16&15],Wo[e>>>12&15],Wo[e>>>8&15],Wo[e>>>4&15],Wo[e&15],Wo[t>>>28],Wo[t>>>24&15],Wo[t>>>20&15],Wo[t>>>16&15],Wo[t>>>12&15],Wo[t>>>8&15],Wo[t>>>4&15],Wo[t&15],Wo[n>>>28],Wo[n>>>24&15],Wo[n>>>20&15],Wo[n>>>16&15],Wo[n>>>12&15],Wo[n>>>8&15],Wo[n>>>4&15],Wo[n&15],Wo[r>>>28],Wo[r>>>24&15],Wo[r>>>20&15],Wo[r>>>16&15],Wo[r>>>12&15],Wo[r>>>8&15],Wo[r>>>4&15],Wo[r&15])},Yo=`effect/Tracer/ParentSpan`;var Xo=class extends (/*#__PURE__*/ P()(Yo,{fiberCached:!0})){};const Zo=e=>e,Qo=e=>({_tag:`ExternalSpan`,spanId:e.spanId,traceId:e.traceId,sampled:e.sampled??!0,annotations:e.annotations??ia()}),$o=/*#__PURE__*/ _a(`effect/Tracer/DisablePropagation`,{defaultValue:It}),es=/*#__PURE__*/ _a(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),ts=/*#__PURE__*/ _a(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),ns=`effect/Tracer`,rs=/*#__PURE__*/ _a(ns,{fiberCached:!0,defaultValue:()=>is}),is=/*#__PURE__*/ Zo({span:e=>new as(e)});var as=class{_tag=`Span`;sampled;name;parent;annotations;links;startTime;kind;status;_traceId=void 0;_spanId=void 0;_attributes=void 0;_events=void 0;constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime}}get traceId(){return this._traceId??=zi(this.parent)?.traceId??Uo(32)}get spanId(){return this._spanId??=Uo(16)}get attributes(){return this._attributes??=/* @__PURE__ */ new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}};const os=/*#__PURE__*/ _a(`effect/ErrorReporter/CurrentErrorReporters`,{defaultValue:()=>/* @__PURE__ */ new Set}),ss=/*#__PURE__*/ _a(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:Lt}),cs=/*#__PURE__*/ _a(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:Ft}),ls=/*#__PURE__*/ _a(`effect/References/TracerTimingEnabled`,{defaultValue:Ft}),us=/*#__PURE__*/ _a(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),ds=/*#__PURE__*/ _a(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),fs=/*#__PURE__*/ _a(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),ps=/*#__PURE__*/ _a(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),Ate=/*#__PURE__*/ _a(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),jte=/*#__PURE__*/ _a(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),ms=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=nr();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};rr(3);let n=/* @__PURE__ */ Error();return rr(t),{...e,captureStackTrace:Mte(()=>n.stack)}},hs=e=>t=>{let n;return()=>{if(n!==void 0)return n;let r=t();if(!r)return;let i=r.split(`
|
|
8
|
+
`);if(i[e]!==void 0)return n=i[e].trim(),n}},Mte=/*#__PURE__*/ hs(3);var gs=class extends Or{constructor(e,t=kr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[kn](e){return Vr(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[un](){return vn(`${this._tag}:${this.fiberId}`)}};const Nte=e=>new gs(e),_s=e=>new Er([new gs(e)]),Pte=e=>{let t=e.reasons.find(zr);return t?ba(t):xa(e)},vs=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return ba(n.error)}return xa(e)},ys=e=>e.reasons.some(Br),Fte=e=>{let t=e.reasons.find(Br);return t?ba(t.defect):xa(e)},bs=e=>e.reasons.some(Vr),xs=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=/* @__PURE__ */ new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?ba(t):xa(e)},Ite=e=>{let t=xs(e);return Ca(t)?Lte:t.success},Lte=/*#__PURE__*/ new Set,Rte=e=>e.reasons.length>0&&e.reasons.every(Vr),zte=e=>ta(e.annotations),Bte=/*#__PURE__*/ j(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>zr(e)?(n=!0,new Ar(t(e.error),e.annotations)):e);return n?jr(r):e}),Ss=e=>{let t;for(let n of e.reasons){if(n._tag===`Fail`)return n.error;n._tag===`Die`&&(t??=n)}return t===void 0?e.reasons.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`):t.defect},Vte=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=nr();i!==0&&rr(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(Cs(i._tag===`Die`?i.defect:i.error,i.annotations,t));if(n.length===0){let e=/* @__PURE__ */ Error(`The fiber was interrupted by:`);e.name=`InterruptCause`,e.stack=Gte(e,r);let i=new globalThis.Error(`All fibers interrupted without error`,{cause:e});i.name=`InterruptError`,i.stack=`${i.name}: ${i.message}`,n.push(Cs(i,r[0].annotations,t))}}finally{i!==0&&rr(i)}return n},Cs=(e,t,n)=>{let r=typeof e,i;if(e&&r===`object`){if(i=new globalThis.Error(Hte(e),{cause:e.cause?Cs(e.cause):void 0}),typeof e.name==`string`&&(i.name=e.name),typeof e.stack==`string`)i.stack=Wte(e.stack,i,t);else{let e=`${i.name}: ${i.message}`;i.stack=t?ws(e,t):e}n?.includeCauseInStack&&(i.stack=Ds(i));for(let t of Object.keys(e))t in i||(i[t]=e[t])}else{i=new globalThis.Error(e?r===`string`?e:Zn(e):`Unknown error: ${e}`);let n=`${i.name}: ${i.message}`;i.stack=t?ws(n,t):n}return i},Hte=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return Zn(e)},Ute=/\((.*)\)/g,Wte=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
|
|
9
|
+
`),a=[r];for(let e=1;e<i.length&&!/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[e]);e++)a.push(i[e]);return n?ws(a.join(`
|
|
10
|
+
`),n):a.join(`
|
|
11
|
+
`)},ws=(e,t)=>{let n=t?.get(Kr.key);return n&&(e=`${e}\n${Ts(n)}`),e},Gte=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(qr.key);n.push(` at fiber (${t})`),r&&n.push(Ts(r))}return n.join(`
|
|
12
|
+
`)},Ts=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Ute),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
|
|
13
|
+
`)},Es=e=>Vte(e).map(Ds).join(`
|
|
14
|
+
`),Ds=e=>e.cause?`${e.stack} {\n${Os(e.cause,` `)}\n}`:e.stack,Os=(e,t)=>{let n=e.stack.split(`
|
|
15
|
+
`),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${Os(e.cause,`${t} `)}\n${t}}`),r},ks=`~effect/Fiber`,Kte={_A:M,_E:M},qte={id:0},As=/*#__PURE__*/ (()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),js=()=>As===void 0?void 0:new As(`effect/Fiber`),Ms=()=>globalThis[Gn];var Ns=class{constructor(e,t=!0){this.setContext(e),this.id=++qte.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[ks](){return Kte}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return da(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Rt):(this._observers===void 0?this._observers=[e]:this._observers.push(e),()=>this.removeObserver(e))}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=_s(e);this.cache.stackFrame&&(n=Rr(n,aa(Kr,this.cache.stackFrame))),t&&(n=Rr(n,t)),this._interruptedCause=this._interruptedCause?Pr(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(Vs(this._interruptedCause)))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;if(this._asyncContext!==void 0){let t=this._asyncContext;return this._asyncContext=void 0,t.runInAsyncScope(this.evaluate,this,e)}if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===_r){this._asyncContext=js();return}let n=Ps.interruptChildren&&Ps.interruptChildren(this);if(n!==void 0)return this.evaluate(_c(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent&&=(this._parent._children?.delete(this),void 0),this._observers!==void 0){let e=this._observers;this._observers=void 0;for(let n=0;n<e.length;n++)e[n](t)}this._stack.length=0,this._children=void 0,this.context=ia()}runLoop(e){let t=globalThis[Gn];globalThis[Gn]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{for(;;)try{this._deferredInterrupt&&(this._deferredInterrupt=!1,i=Vs(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=_c(Gs,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[pr](this),i===_r){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return _r}}catch(e){if(!N(i,`~effect/Effect/evaluate`))return Xr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=Xr(e)}}finally{this._running=n,globalThis[Gn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Yte;for(;;){let t=this._stack.pop();if(!t)return;let n=t[gr];if(n!==void 0){let r=n.call(t,this);if(r)return r[e]=r,r}if(t[e])return t}}succeedWith(e){if(!(++this.currentOpCount&Xte-1))return Gr(e);let t=this.getCont(mr);return t?t[mr](e,this):this.yieldWith(Gr(e))}yieldWith(e){return this._yielded=e,_r}children(){return this._children??=/* @__PURE__ */ new Set}pipe(){return jt(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&ete(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Jte(e);this.cache?.scheduler!==r.scheduler&&(this._dispatcher=void 0),this.cache=r}get currentSpanLocal(){let e=this.cache.span;return e?._tag===`Span`?e:void 0}};const Jte=e=>{let t=la(e,ns);return{scheduler:da(e,Eo),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:da(e,cs),span:la(e,Yo),logLevel:da(e,ps),minimumLogLevel:da(e,Ate),stackFrame:da(e,ss),runtimeMetrics:la(e,`effect/Metric/FiberRuntimeMetrics`),maxOpsBeforeYield:da(e,No),preventYield:da(e,Po)}},Yte={[mr](e,t){return Vs(t._interruptedCause)},[hr](e,t){return Vs(t._interruptedCause)}},Xte=32,Ps={interruptChildren:void 0},Fs=e=>{if(!e.cache.stackFrame)return;let t=/* @__PURE__ */ new Map;return t.set(qr.key,e.cache.stackFrame),ta(t)},Zte=e=>{if(e._children!==void 0&&e._children.size!==0)return zs(e._children)},Qte=e=>{let t=e;return t._exit?Bs(t._exit):Zs(n=>t._exit?n(Bs(t._exit)):Us(e.addObserver(e=>n(Bs(e)))))},Is=e=>Zs(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;)if(e.value._exit)r.push(e.value._exit),e=n.next();else{i=e.value.addObserver(e=>{r.push(e),a()});return}t(Bs(r))}return a(),Us(()=>i?.())}),Ls=e=>{let t=e;return t._exit?t._exit:Zs(n=>t._exit?n(t._exit):Us(e.addObserver(n)))},Rs=e=>Zr(t=>$te(e,t.id)),$te=/*#__PURE__*/ j(e=>N(e[0],ks),(e,t,n)=>Zr(r=>{let i=Fs(r);return i=i&&n?ha(i,n):i??n,e.interruptUnsafe(t,i),hc(Qte(e))})),zs=e=>Zr(t=>{let n=Fs(t),r=Pa();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return hc(Is(r))}),Bs=Gr,Vs=Jr,Hs=Yr,Us=/*#__PURE__*/ Ur({op:`Sync`,[pr](e){let t=this[fr](),n=e.getCont(mr);return n?n[mr](t,e):e.yieldWith(Gr(t))}}),Ws=/*#__PURE__*/ Ur({op:`Suspend`,[pr](e){return this[fr]()}}),ene=/*#__PURE__*/ cte({onFailure:Hs,onSuccess:Bs}),Gs=/*#__PURE__*/ (/* @__PURE__ */ Ur({op:`Yield`,[pr](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Cc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}}))(0),Ks=/*#__PURE__*/ Bs(/*#__PURE__*/ Ai()),tne=e=>Ws(()=>Vs(e())),qs=e=>Xr(e),Js=e=>Ws(()=>Hs(e())),Ys=/*#__PURE__*/ Bs(void 0),nne=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Gu(e,`An error occurred in Effect.try`):e.catch;return Ws(()=>{try{return Bs(t())}catch(e){return Hs(n(e))}})},rne=e=>Xs(function(t,n){e(n).then(e=>t(Bs(e)),e=>t(qs(e)))},e.length!==0),ine=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Gu(e,`An error occurred in Effect.tryPromise`):e.catch;return Xs(function(e,r){let i=e=>Ws(()=>{try{return Hs(ar(()=>n(e)))}catch(e){return qs(e)}});try{t(r).then(t=>e(Bs(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},ane=e=>Zr(t=>e(t.id)),Xs=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Hr({op:`Async`,[pr](e){let t=!1,n=!1,r=this.withSignal?new AbortController:void 0,i=this.register.call(e.cache.scheduler,r=>{t||(t=!0,n?e.evaluate(r):n=r)},r?.signal);return n===!1?(n=!0,e._yielded=()=>{t=!0},r===void 0&&i===void 0||e._stack.push(one(()=>(t=!0,r?.abort(),i??Cc))),_r):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),one=/*#__PURE__*/ Ur({op:`AsyncFinalizer`,[gr](e){e.interruptible&&(e.interruptible=!1,e._stack.push(Nl))},[hr](e,t){return bs(e)?_c($c(Jr(e),this[fr]()),()=>Vs(e)):Vs(e)}}),Zs=e=>Xs(e,e.length>=2),Qs=/*#__PURE__*/ Zs(Rt),sne=(...e)=>{if(e.length===1){let t=e[0];return Ws(()=>ic(t()))}let[t,n]=e;return Ws(()=>ic(n.call(t.self)))},$s=(e,...t)=>{let n=t.length===0?function(){return Ws(()=>ic(e.apply(this,arguments)))}:function(){let n=Ws(()=>ic(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return ec(e.length,n)},ec=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),tc=/*#__PURE__*/ hs(2),cne=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=nr(),i;return r!==0&&(rr(2),i=new globalThis.Error,rr(r)),e?(r,...a)=>nc(t,r,i,a,e,n):nc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},nc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?tc(()=>n.stack):Lt;return ec(o.length,function(...t){let n=Ws(()=>{let e=o.apply(this,arguments);return br(e)?e:ic(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!br(n))return n;let l=nr(),u;return l!==0&&(rr(2),u=new globalThis.Error,rr(l)),Ec(i?Su(e,a,e=>Cu(n,e)):n,ss,t=>({name:e,stack:u?tc(()=>u.stack):Lt,parent:{name:s,stack:c,parent:t}}))})},lne=(e,...t)=>ec(e.length,t.length===0?function(){return rc(()=>e.apply(this,arguments))}:function(){let n=rc(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),rc=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return Bs(r.value);let i=r.value;if(i&&i._tag===`Success`)n=i.value;else{if(i&&i._tag===`Failure`)return r.value;{let n=!0;return Ws(()=>n?(n=!1,_c(r.value,e=>ic(t,e))):Ws(()=>ic(e())))}}}}catch(e){return qs(e)}},ic=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Hr({op:`Iterator`,[mr](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return Bs(r.value);if(!vc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[pr](e){return this[mr](this.initial,e)}}),t=function(e,t){this.iterator=e,this.initial=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),ac=/*#__PURE__*/ j(2,(e,t)=>new sc(e,cc,Bs(t))),oc=function(e){return e._stack.push(this),this[fr]},une=/*#__PURE__*/ Hr({op:`OnSuccess`,[pr]:oc}),sc=function(e,t,n){this[fr]=e,this[mr]=t,this.payload=n};sc.prototype=une;const cc=function(){return this.payload},lc=function(e,t){return t.succeedWith(this.payload)},uc=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ nr();if(e===0)return!1;let t=`~effect/Effect/stackProbe`,n={[t]:function(){return/* @__PURE__ */ Error()}};rr(1);let r=/*#__PURE__*/ n[t]();return rr(e),r.stack?.includes(`[as `+t+`]`)===!0})(),dne=function(e,t){let n=this.payload;return t.succeedWith(uc?n(e):ar(()=>n(e)))},dc=function(e){let t=this.payload;return t(e)},fne=function(e){let t=this.payload;return new sc(t(e),lc,e)},pne=function(e){return new sc(this.payload,lc,e)},fc=e=>yc(e,ji),pc=/*#__PURE__*/ j(2,(e,t)=>new sc(e,br(t)?cc:dc,t)),mc=/*#__PURE__*/ j(2,(e,t)=>new sc(e,br(t)?pne:fne,t)),hc=e=>new sc(e,cc,Cc),mne=(e,t)=>Zr(n=>{let r=/* @__PURE__ */ new Set;return bl(n,()=>r.size===0?void 0:zs(r)),Zs(i=>{let a=ka(e),o=a.length,s=0,c=!1,l=[],u=(e,r,a)=>{if(s++,e._tag===`Failure`){l.push(...e.cause.reasons),s>=o&&i(Vs(jr(l)));return}let u=!c;c=!0,i(e),u&&t?.onWinner&&t.onWinner({fiber:r,index:a,parentFiber:n})};for(let e=0;e<o;e++){let t=Zl(n,a[e],!0,!0,!1);if(r.add(t),t.addObserver(n=>{r.delete(t),u(n,t,e)}),c)break}})}),hne=(e,t)=>Zr(n=>{let r=/* @__PURE__ */ new Set;return bl(n,()=>r.size===0?void 0:zs(r)),Zs(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=Zl(n,s,!0,!0,!1);r.add(c),c.addObserver(o=>{r.delete(c);let s=!a;a=!0,i(o),s&&t?.onWinner&&t.onWinner({fiber:c,index:e,parentFiber:n})})}})}),gne=/*#__PURE__*/ j(e=>br(e[1]),(e,t,n)=>mne([e,t],n)),gc=/*#__PURE__*/ j(e=>br(e[1]),(e,t,n)=>hne([e,t],n)),_c=/*#__PURE__*/ j(2,(e,t)=>new sc(e,dc,t)),_ne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?e._tag===`Success`?t.onSuccess(e.value):t.onFailure(e.cause):Rc(e,t)),vc=e=>e[lr]!==void 0,vne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?e._tag===`Success`?t(e.value):e:_c(e,t)),yne=e=>_c(e,M),yc=/*#__PURE__*/ j(2,(e,t)=>new sc(e,dne,t)),bne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?Ene(e,t):yc(e,t)),xne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?Dne(e,t):Ic(e,t)),Sne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?One(e,t):qne(e,t)),Cne=/*#__PURE__*/ j(2,(e,t)=>{if(vc(e)){if(e._tag===`Success`)return e;let n=vs(e.cause);return Ca(n)?e:t(n.success)}return Pc(e,t)}),bc=e=>Jr(_s(e)),xc=e=>e._tag===`Success`,wne=e=>e._tag===`Failure`,Tne=e=>e._tag===`Failure`?ba(e.cause):xa(e),Sc=e=>e._tag===`Failure`&&bs(e.cause),Cc=/*#__PURE__*/ Gr(void 0),Ene=/*#__PURE__*/ j(2,(e,t)=>e._tag===`Success`?Gr(t(e.value)):e),Dne=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return e;let n=vs(e.cause);return Ca(n)?e:Yr(t(n.success))}),One=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return Gr(t.onSuccess(e.value));let n=vs(e.cause);return Ca(n)?e:Yr(t.onFailure(n.success))}),kne=/*#__PURE__*/ j(2,(e,t)=>xc(e)?t:e),wc=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Cc:Jr(jr(t))},Ane=e=>e,jne=e=>Zr(t=>Bs(ma(t.context,e))),Tc=/*#__PURE__*/ j(2,(e,t)=>Zr(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),bl(n,()=>{n.setContext(r)})),e})),Ec=/*#__PURE__*/ j(3,(e,t,n)=>Tc(e,e=>{let r=ua(e,t),i=n(r);return r===i?e:oa(e,t,i)})),Mne=()=>Nne,Nne=/*#__PURE__*/ Zr(e=>Bs(e.context)),Dc=e=>Zr(t=>e(t.context)),Pne=/*#__PURE__*/ j(2,(e,t)=>Tc(e,Pt(t))),Oc=/*#__PURE__*/ j(2,(e,t)=>vc(e)?e:Tc(e,ha(t))),kc=function(){return arguments.length===1?j(2,(e,t)=>Ac(e,arguments[0],t)):j(3,(e,t,n)=>Ac(e,t,n)).apply(this,arguments)},Ac=(e,t,n)=>Tc(e,oa(t,n)),Fne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>Yl(e,t,n?e=>Hs(n(e)):()=>Hs(new zee))),Ine=/*#__PURE__*/ j(2,(e,t)=>_c(t,t=>t?fc(e):Ks)),Lne=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>Vl({while:Ft,body:Pt(t?.disableYield?e:_c(e,e=>Gs)),step:Rt})),jc=/*#__PURE__*/ j(2,(e,t)=>new Mc(e,t.length===1?t:e=>t(e))),Rne=/*#__PURE__*/ Hr({op:`OnFailure`,[pr]:oc}),Mc=function(e,t){this[fr]=e,this[hr]=t};Mc.prototype=Rne;const zne=/*#__PURE__*/ j(3,(e,t,n)=>jc(e,e=>t(e)?n(e):Vs(e))),Nc=/*#__PURE__*/ j(3,(e,t,n)=>jc(e,e=>{let r=t(e);return Ca(r)?Vs(r.failure):n(r.success,e)})),Pc=/*#__PURE__*/ j(2,(e,t)=>Nc(e,vs,e=>t(e))),Bne=/*#__PURE__*/ j(2,(e,t)=>Nc(e,Fte,t)),Vne=/*#__PURE__*/ j(2,(e,t)=>jc(e,e=>pc(t(e),Vs(e)))),Hne=/*#__PURE__*/ j(3,(e,t,n)=>jc(e,e=>{let r=t(e);return Ca(r)?Vs(e):pc(n(r.success,e),Vs(e))})),Une=/*#__PURE__*/ j(2,(e,t)=>Hne(e,vs,e=>t(e))),Fc=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n,r)=>jc(e,e=>{let i=vs(e);return Ca(i)?Vs(i.failure):t(i.success)?n(i.success):r?r(i.success):Vs(e)})),Wne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n,r)=>jc(e,e=>{let i=vs(e);if(Ca(i))return Vs(i.failure);let a=t(i.success);return Ca(a)?r?r(a.failure):Vs(e):n(a.success)})),Gne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n,r)=>{let i=Array.isArray(t)?e=>N(e,`_tag`)&&t.includes(e._tag):ln(t);return Fc(e,i,n,r)}),Kne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>{let r;return Wne(e,e=>(r??=Object.keys(t),N(e,`_tag`)&&Jt(e._tag)&&r.includes(e._tag)?ba(e):xa(e)),e=>t[e._tag](e),n)}),Ic=/*#__PURE__*/ j(2,(e,t)=>Pc(e,e=>Js(()=>t(e)))),qne=/*#__PURE__*/ j(2,(e,t)=>Bc(e,{onFailure:e=>Js(()=>t.onFailure(e)),onSuccess:e=>Us(()=>t.onSuccess(e))})),Jne=e=>Pc(e,qs),Yne=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>{if(!t?.log)return Bc(e,{onFailure:e=>Ys,onSuccess:e=>Ys});let n=td(t.log===!0?void 0:t.log);return Rc(e,{onFailure(e){let r=Pte(e);return Ca(r)?Vs(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>Ys})}),Xne=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>{if(!t?.log)return Rc(e,{onFailure:e=>Ys,onSuccess:e=>Ys});let n=td(t.log===!0?void 0:t.log);return Rc(e,{onFailure:e=>t.message===void 0?n(e):n(t.message,e),onSuccess:e=>Ys})}),Zne=e=>Vc(e,{onFailure:Ai,onSuccess:ji}),Lc=e=>tre(e,{onFailure:xa,onSuccess:ba}),Rc=/*#__PURE__*/ j(2,(e,t)=>new zc(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),Qne=/*#__PURE__*/ Hr({op:`OnSuccessAndFailure`,[pr]:oc}),zc=function(e,t,n){this[fr]=e,this[mr]=t,this[hr]=n};zc.prototype=Qne;const $ne=function(e,t){let n=this.payload;return t.succeedWith(uc?n.onSuccess(e):ar(()=>n.onSuccess(e)))},ere=/*#__PURE__*/ ((e,t)=>{let n=Hr({op:e,[pr]:oc,[mr]:$ne,[hr]:t}),r=function(e,t){this[fr]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=e.reasons.find(zr);if(n===void 0)return Vs(e);let r=this.payload;return t.succeedWith(uc?r.onFailure(n.error):ar(()=>r.onFailure(n.error)))}),Bc=/*#__PURE__*/ j(2,(e,t)=>Rc(e,{onFailure:e=>{let n=e.reasons.find(zr);return n?t.onFailure(n.error):Vs(e)},onSuccess:t.onSuccess})),Vc=/*#__PURE__*/ j(2,(e,t)=>new ere(e,t)),tre=/*#__PURE__*/ j(2,(e,t)=>{if(vc(e)){if(e._tag===`Success`)return Gr(t.onSuccess(e.value));let n=vs(e.cause);return Ca(n)?e:Gr(t.onFailure(n.success))}return Vc(e,t)}),Hc=e=>vc(e)?Gr(e):nre(e),nre=/*#__PURE__*/ Ur({op:`Exit`,[pr](e){return e._stack.push(this),this[fr]},[mr](e,t,n){return t.succeedWith(n??Gr(e))},[hr](e,t,n){return t.succeedWith(n??Jr(e))}}),rre=/*#__PURE__*/ j(2,(e,t)=>pc(Pu(t),e)),Uc=/*#__PURE__*/ j(2,(e,t)=>_c(Kc(e,t.duration),e=>Mi(e)?t.orElse():Bs(e.value))),Wc=e=>new Lu(`Operation timed out after '${To(e)}'`),Gc=/*#__PURE__*/ j(2,(e,t)=>{let n=Ja(t);return Uc(e,{duration:n,orElse:()=>Hs(Wc(n))})}),Kc=/*#__PURE__*/ j(2,(e,t)=>gc(fc(e),ac(Pu(t),Ai()))),qc=`~effect/Scope`,Jc=`~effect/Scope/Closeable`,Yc=/*#__PURE__*/ P(`effect/Scope`),Xc=(e,t)=>Zr(n=>(Il(n),Zc(e,t)??Ys)),Zc=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&ol(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Qc(n.finalizer,t);let r=n.finalizers;return r.size===1?Qc(r.values().next().value,t):el(e,r,t)},Qc=(e,t)=>{try{return e(t)}catch(e){return Xr(e)}},$c=(e,t)=>xc(e)?t:jc(t,t=>Vs(Nr(e.cause,t))),el=/*#__PURE__*/ $s(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Ms();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*Hc(Qc(s,n))):i.push(Zl(o,Qc(s,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Is(i)),yield*wc(r)}),tl=(e,t)=>Us(()=>nl(e,t)),nl=(e,t)=>{let n=cl(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(al(e,n,e=>Xc(n,e)),n)},rl=(e,t)=>Ws(()=>e.state._tag===`Closed`?t(e.state.exit):(al(e,{},t),Ys)),il=(e,t)=>rl(e,Pt(t)),al=(e,t,n)=>{if(e.state._tag===`Empty`)e.state={_tag:`Open`,finalizerKey:t,finalizer:n,finalizers:void 0};else if(e.state._tag===`Open`){let r=e.state;r.finalizer===void 0||(r.finalizers=/* @__PURE__ */ new Map([[r.finalizerKey,r.finalizer]]),r.finalizerKey=void 0,r.finalizer=void 0),r.finalizers.set(t,n)}},ol=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=ll:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=ll))},sl=e=>cl(e,void 0),cl=(e=`sequential`,t)=>({[Jc]:Jc,[qc]:qc,strategy:e,parent:t,state:ll}),ll={_tag:`Empty`},ul=e=>Us(()=>sl(e)),dl=Yc,fl=/*#__PURE__*/ kc(Yc),pl=e=>Zr(t=>{let n=t.context,r=sl();return t.setContext(oa(t.context,Yc,r)),bl(t,e=>(t.setContext(n),Zc(r,e))),e}),ml=/*#__PURE__*/ j(2,(e,t)=>xl(fl(e,t),e=>Ws(()=>Zc(t,e)??Ys))),hl=e=>Ws(()=>{let t=sl();return xl(e(t),e=>Ws(()=>Zc(t,e)??Ys))}),gl=(e,t,n)=>Dc(r=>zl(i=>_c(dl,a=>mc(n?.interruptible?i(e):e,e=>rl(a,n=>Oc(t(e,n),r)))))),_l=e=>_c(dl,t=>Dc(n=>rl(t,t=>Oc(e(t),n)))),vl=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Hr({op:`OnExit`,[pr](e){return e._stack.push(this),this.effect},[gr](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(Nl),e.interruptible=!1)},[mr](e,t,n){n??=Gr(e);let r;try{r=this.onExit(n)}catch(e){r=Xr(e)}return r?_c(r,e=>n):n},[hr](e,t,n){n??=Jr(e);let r;try{r=this.onExit(n)}catch(e){r=Xr(e)}return r?_c($c(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),yl=(e,t,n)=>new vl(e,t,n),bl=(e,t)=>{e._stack.push(new vl(void 0,t,void 0))},xl=/*#__PURE__*/ j(2,yl),Sl=/*#__PURE__*/ j(2,(e,t)=>xl(e,e=>t)),Cl=/*#__PURE__*/ j(3,(e,t,n)=>xl(e,e=>{let r=t(e);return Ca(r)?Ys:n(r.success,e)})),wl=/*#__PURE__*/ j(2,(e,t)=>Cl(e,Tne,t)),Tl=/*#__PURE__*/ j(3,(e,t,n)=>xl(e,e=>{if(e._tag!==`Failure`)return Ys;let r=t(e.cause);return Ca(r)?Ys:n(r.success,e.cause)})),El=/*#__PURE__*/ j(2,(e,t)=>Tl(xs,t)(e)),Dl=/*#__PURE__*/ Pt(1/0),Ol=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,bl(e,()=>{if(!(--t.awaiters>0||i!==t))return i=void 0,Rs(t.fiber)}),Ls(t.fiber));return[Zr(o=>{if(i!==void 0)return o===i.fiber?Ls(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(Du).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(Du),c={fiber:new Ns(o.context),awaiters:0};i=c;let l=a(o,c);return c.fiber.evaluate(yl(e,e=>{if(i!==c||(i=void 0,Sc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),Us(()=>{r=void 0})]},kl=e=>Us(()=>Ol(e,Dl)[0]),Al=/*#__PURE__*/ Zr(e=>Vs(_s(e.id))),jl=e=>Zr(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(Nl)),e)),Ml=/*#__PURE__*/ Ur({op:`SetInterruptible`,[gr](e){if(e.interruptible=this[fr],e._interruptedCause&&e.interruptible)return()=>Vs(e._interruptedCause)}}),Nl=/*#__PURE__*/ Ml(!0),Pl=/*#__PURE__*/ Ml(!1),Fl=e=>{if(e.interruptible=!0,e._stack.push(Pl),e._interruptedCause)return Vs(e._interruptedCause)},Il=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(Nl))},Ll=e=>{let t=e;if(!t.interruptible)return Fl(t)},Rl=e=>Zr(t=>t.interruptible?e:Fl(t)??e),zl=e=>Zr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(Nl),e(Rl)):e(M)),Bl=(e,t)=>xee(e)?t?.mode===`result`?Hl(e,Lc,t):Hl(e,M,t):t?.discard?t.mode===`result`?Hl(Object.values(e),Lc,t):Hl(Object.values(e),M,t):Ws(()=>{let n={};return ac(Hl(Object.entries(e),([e,r])=>yc(t?.mode===`result`?Lc(r):r,t=>{or(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),Vl=/*#__PURE__*/ Ur({op:`While`,[mr](e,t){return this[fr].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[fr].body()):Cc},[pr](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[fr].body()):Cc}}),Hl=/*#__PURE__*/ j(e=>typeof e[1]==`function`,(e,t,n)=>Ws(()=>{let r=Wl(n?.concurrency);if(r===1)return Ul(e,t,n);let i=ka(e),a=i.length;if(a===0)return n?.discard?Ys:Bs([]);let o=n?.discard?void 0:Array(a),s=Jl({f:t,out:o},i,{concurrency:r});return s?ac(s,o):Bs(o)})),Ul=(e,t,n)=>Ws(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return ac(Vl({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),Wl=e=>e===`unbounded`?1/0:Math.max(1,e??1),Gl=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>_c(Hc(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??Ys),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!vc(c))return r(e,i,a,o,c);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return i},Kl=e=>{let t=e.onItem,n=e.step;return(e,r,i)=>{let a=0,o=i.end??r.length,s=i.concurrency,c=!1,l,u,d,f,p,m=e=>{let t=Xr(e);return f=t,c=!0,u&&u.size>0?_c(jl(zs(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(vc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=Zl(l,g,!0,!0,`inherit`);if(t._exit){if(f=n(e,o,t._exit,a),f)break;continue}u.add(t);let r=a;if(t.addObserver(a=>{u.delete(t);try{if(f){if(a._tag===`Failure`){let e=a.cause.reasons.filter(e=>e._tag!==`Interrupt`);if(e.length>0){let t=jr(e);f=Jr(f._tag===`Failure`?Nr(f.cause,t):t)}}}else{let t=n(e,o,a,r);t&&(f=t,h())}if(i){let e=h();e&&d(e)}else c&&u.size===0&&d(f??Ys)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return Zs(e=>{l=Ms(),u=/* @__PURE__ */ new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Ws(()=>(f??=Cc,_c(u?zs(u):Ys,()=>f?._tag===`Failure`?f:Ys)))})}if(c=!0,f){if(u&&u.size>0){let e=Fs(l);u.forEach(t=>t.interruptUnsafe(l.id,e));return}if(d||f._tag===`Failure`)return f}else if(d){if(u)u.size===0&&d(Ys);else return Cc}};return h()}},ql=()=>e=>Kl(e),Jl=/*#__PURE__*/ Kl({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag===`Failure`)return n;e.out&&(e.out[r]=n.value)}}),Yl=/*#__PURE__*/ j(3,(e,t,n)=>_c(e,e=>t(e)?Bs(e):n(e))),Xl=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>Zr(n=>(od(),Bs(Zl(n,e,t?.startImmediately,!1,t?.uninterruptible??!1))))),Zl=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Ns(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=js(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},Ql=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>Zr(r=>{let i=Zl(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};al(t,e,()=>ane(e=>e===i.id?Ys:Rs(i))),i.addObserver(()=>ol(t,e))}else i.interruptUnsafe(r.id,Fs(r))}return Bs(i)})),$l=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>_c(dl,n=>Ql(e,n,t))),eu=e=>(t,n)=>{let r=new Ns(n?.scheduler?oa(e,Eo,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},tu=/*#__PURE__*/ j(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(ol(t,e),al(t,e,()=>Rs(e)),e.addObserver(()=>ol(t,e)),e)),nu=/*#__PURE__*/ eu(/*#__PURE__*/ ia()),ru=e=>{let t=eu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},iu=e=>{let t=ru(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw Ss(e.cause);return e.value})},au=/*#__PURE__*/ iu(/*#__PURE__*/ ia()),ou=e=>{let t=eu(e);return e=>{if(vc(e))return e;let n=new jo(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??Xr(new Uu(r))}},su=/*#__PURE__*/ ou(/*#__PURE__*/ ia()),cu=/*#__PURE__*/ (e=>{let t=ou(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw Ss(n.cause);return n.value}})(/*#__PURE__*/ ia()),lu=/*#__PURE__*/ Bs(!0),uu=/*#__PURE__*/ Bs(!1);var du=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return lu;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let e=0;e<this.waiters.length;e++)this.scheduled.push(this.waiters[e]);return this.waiters=[],lu}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](Cc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Cc)}open=/*#__PURE__*/ Zr(e=>this._isOpen?uu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=/*#__PURE__*/ Zr(e=>this._isOpen?uu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=/*#__PURE__*/ Zs(e=>this._isOpen?e(Ys):(this.waiters.push(e),Us(()=>{let t=this.waiters.indexOf(e);t===-1?this.scheduled!==void 0&&(t=this.scheduled.indexOf(e),t!==-1&&this.scheduled.splice(t,1)):this.waiters.splice(t,1)})));closeUnsafe(){return this._isOpen?(this._isOpen=!1,!0):!1}close=/*#__PURE__*/ Us(()=>this.closeUnsafe());whenOpen=e=>_c(this.await,()=>e);isOpen(){return this._isOpen}};const fu=e=>new du(e??!1),pu=e=>Us(()=>fu(e)),mu=/*#__PURE__*/ BigInt(0),hu={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:mu,endTime:mu,exit:Cc},attributes:/*#__PURE__*/ new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},gu=e=>Object.assign(Object.create(hu),e),_u=e=>e?da(e.annotations,$o)?e._tag===`Span`?_u(zi(e.parent)):Ai():ji(e):Ai(),vu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&da(n.annotations,$o),i=n?.parent===void 0?n?.root?Ai():_u(e.cache.span):ji(n.parent),a;if(r)a=gu({name:t,parent:i,annotations:oa(n?.annotations??ia(),$o,!0)});else{let r=e.cache.tracer??is,o=e.getRef(Du),s=e.getRef(ls),c=e.getRef(us),l=e.getRef(ds),u=n?.level??e.getRef(es),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??ia(),links:d,startTime:s?o.currentTimeNanosUnsafe():mu,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(Ni(i)&&i.value.sampled===!1?!1:!Ju(e.getRef(ts),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},yu=(e,t)=>jl(Zr(n=>{let r=ua(n.context,Yc),i=vu(n,e,t??{}),a=n.getRef(Du),o=n.getRef(ls);return ac(rl(r,e=>xu(i,e,a,o)),i)})),bu=(e,t)=>(t=typeof t==`function`?t:Lt,Ec(ss,n=>({name:e,stack:t,parent:n}))),xu=(e,t,n,r)=>Us(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():mu,t)}),Su=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return Zr(t=>{let i=vu(t,e,n),a=t.getRef(Du),o=t.getRef(ls);return bl(t,e=>xu(i,e,a,o)),r(i)})},Cu=/*#__PURE__*/ kc(Xo),wu=function(){let e=br(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=M;return t._tag===`Span`&&(n=ms(n),r=bu(t.name,n?.captureStackTrace)),e?Cu(r(arguments[0]),t):e=>Cu(r(e),t)},Tu=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=ms(arguments[2]);if(e){let e=arguments[0];return Su(t,arguments[2],t=>wu(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>Su(t,r?r(...a):i,t=>wu(e,t,n))},Eu=(...e)=>Zr(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return Ys}),Du=/*#__PURE__*/ _a(`effect/Clock`,{defaultValue:()=>new ku}),Ou=2**31-1;var ku=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=/*#__PURE__*/ Us(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Mu()}currentTimeNanos=/*#__PURE__*/ Us(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return ju()}monotonicTimeNanos=/*#__PURE__*/ Us(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(_o(e))}sleepMillis(e){return e<=0?Gs:Number.isFinite(e)?Zs(t=>{let n=e>Ou?this.sleepMillis(e-Ou):Ys,r=setTimeout(()=>t(n),Math.min(e,Ou));return Us(()=>clearTimeout(r))}):Qs}};const Au=/*#__PURE__*/ BigInt(1e6),ju=/*#__PURE__*/ function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==`function`)return()=>e.bigint();if(typeof performance<`u`&&typeof performance.now==`function`)return()=>BigInt(Math.round(performance.now()*1e6));let t=/*#__PURE__*/ BigInt(0);return()=>{let e=BigInt(Date.now())*Au;return e>t&&(t=e),t}}(),Mu=/*#__PURE__*/ function(){let e=/*#__PURE__*/ BigInt(1e9),t;return()=>{let n=ju(),r=BigInt(Date.now())*Au;if(t===void 0)t=r-n;else{let i=t+n;(r>i?r-i:i-r)>e&&(t=r-n)}return t+n}}(),Nu=e=>Zr(t=>e(t.getRef(Du))),Pu=e=>Nu(t=>t.sleep(Ja(e))),Fu=/*#__PURE__*/ Nu(e=>e.currentTimeMillis),Iu=`~effect/Cause/TimeoutError`;var Lu=class extends (/*#__PURE__*/ $r(`TimeoutError`)){[Iu]=Iu;constructor(e){super({message:e})}};const Ru=`~effect/Cause/IllegalArgumentError`;var zu=class extends (/*#__PURE__*/ $r(`IllegalArgumentError`)){[Ru]=Ru;constructor(e){super({message:e})}};const Bu=`~effect/Cause/ExceededCapacityError`;var Vu=class extends (/*#__PURE__*/ $r(`ExceededCapacityError`)){[Bu]=Bu;constructor(e){super({message:e})}};const Hu=`~effect/Cause/AsyncFiberError`;var Uu=class extends (/*#__PURE__*/ $r(`AsyncFiberError`)){[Hu]=Hu;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};const Wu=`~effect/Cause/UnknownError`;var Gu=class extends (/*#__PURE__*/ $r(`UnknownError`)){[Wu]=Wu;constructor(e,t){super({message:t,cause:e})}};const Ku=/*#__PURE__*/ _a(`effect/Console`,{defaultValue:()=>globalThis.console}),qu=/*#__PURE__*/ Ti(wi,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}}),Ju=/*#__PURE__*/ Di(qu),Yu=/*#__PURE__*/ _a(`effect/Logger/CurrentLoggers`,{defaultValue:()=>/* @__PURE__ */ new Set([id,ad])}),Xu=/*#__PURE__*/ _a(`effect/Logger/LogToStderr`,{defaultValue:It}),Zu={"~effect/Logger":{_Message:M,_Output:M},pipe(){return jt(this,arguments)}},Qu=e=>{let t=Object.create(Zu);return t.log=e,t},$u=e=>e.replace(/[\s="]/g,`_`),ed=(e,t)=>`${$u(e[0])}=${t-e[1]}ms`,td=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];wr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?jr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=Fee),Zr(r=>{let i=e??r.cache.logLevel;if(Ju(r.cache.minimumLogLevel,i))return Ys;let a=r.getRef(Du),o=r.getRef(Yu);if(o.size>0){let e=new Date(a.currentTimeMillisUnsafe());for(let a of o)a.log({cause:n,fiber:r,date:e,logLevel:i,message:t})}return Ys})},nd={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};nd.gray,nd.blue,nd.green,nd.yellow,nd.red,nd.bgBrightRed,nd.black;const rd=e=>`${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}.${e.getMilliseconds().toString().padStart(3,`0`)}`,id=/*#__PURE__*/ Qu(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Es(e));let o=t.getTime(),s=n.getRef(jte),c=``;for(let e of s)c+=` ${ed(e,o)}`;let l=n.getRef(fs);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Ku);(n.getRef(Xu)?u.error:u.log)(`[${rd(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),ad=/*#__PURE__*/ Qu(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Du),a=t.getRef(fs),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))or(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Es(e)),o.event(Nee(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});function od(){Ps.interruptChildren??=Zte}const sd=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>wl(e,e=>Zr(n=>(cd(n,e,t?.defectsOnly),Ys)))),cd=(e,t,n)=>{let r=e.getRef(os);if(r.size===0||n&&!ys(t))return;let i={cause:t,fiber:e,timestamp:e.getRef(Du).currentTimeNanosUnsafe()};r.forEach(e=>e.report(i))},ld=wr,ud=Tr,dd=zr,ire=Br,fd=jr,are=Fr,pd=Lr,md=e=>new Ar(e),hd=e=>new Ir(e),ore=Nte,sre=Rte,gd=Bte,cre=Nr,_d=Ss,lre=vs,vd=ys,yd=bs,ure=Ite,dre=Es,fre=Ree,bd=Bee,xd=ri,Sd=Hee,Cd=zu,pre=Vu,mre=Gu,wd=zte;var Td=class extends (/*#__PURE__*/ P()(`effect/Cause/StackTrace`)){};const Ed=xr,Dd=Gr,Od=Jr,kd=Yr,Ad=Xr,jd=bc,Md=Cc,Nd=xc,Pd=wne,hre=Sc,gre=wc,Fd=`~effect/Deferred`,_re=e=>N(e,Fd),vre={[Fd]:{_A:M,_E:M},pipe(){return jt(this,arguments)}},Id=function(){this.resumes=void 0,this.effect=void 0};Id.prototype=vre;const Ld=()=>new Id,Rd=()=>Us(()=>Ld()),zd=e=>Zs(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),Us(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),Bd=/* @__PURE__ */ j(2,(e,t)=>Us(()=>Wd(e,t))),yre=/*#__PURE__*/ j(2,(e,t)=>Bd(e,Jr(t))),bre=/*#__PURE__*/ j(2,(e,t)=>yre(e,_s(t))),Vd=e=>Us(()=>Hd(e)),Hd=e=>e.effect!==void 0,Ud=/*#__PURE__*/ j(2,(e,t)=>Bd(e,Gr(t))),Wd=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},xre=fs,Gd=ps,Sre=ls,Kd=Yc,Cre=ul,qd=sl,Jd=fl,Yd=rl,Xd=il,Zd=tl,Qd=nl,$d=Xc,ef=Zc,wre=ml,tf=`~effect/Layer/MemoMap`,Tre=(e,t)=>{let n={observers:0,deferred:Ld(),scope:qd(),finalizer:r=>Ws(()=>--n.observers>0?Ys:(e.map.delete(t),$d(n.scope,r)))};return n},nf=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,al(t,{},e.finalizer),!0),Ere={"~effect/Layer":{_ROut:M,_E:M,_RIn:M},pipe(){return jt(this,arguments)}},rf=e=>{let t=Object.create(Ere);return t.build=e,t},af=e=>rf((t,n)=>{let r=Qd(n);return xl(e(t,r),e=>e._tag===`Failure`?$d(r,e):Ys)}),Dre=e=>{let t=af((n,r)=>n.getOrElseMemoize(t,r,e));return t};var of=class{get[tf](){return tf}parent;constructor(e){this.parent=e}map=/*#__PURE__*/ new Map;get(e,t){let n=this.map.get(e);return n?(nf(n,t),n.deferred.effect??zd(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Ws(()=>{let r;return yl(Ws(()=>{let i=this.get(e,t);if(i)return i;let a=Tre(this,e);return nf(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&Wd(r,e)})})}};const sf=()=>new of,Ore=e=>new of(e);var cf=class e extends (/*#__PURE__*/ P()(`effect/Layer/CurrentMemoMap`)){static forkOrCreate(t){let n=ca(t,e);return n?Ore(n):sf()}};const lf=/*#__PURE__*/ j(3,(e,t,n)=>kc(yc(Ws(()=>e.build(t,n)),oa(cf,t)),cf,t)),kre=e=>Zr(t=>lf(e,cf.forkOrCreate(t.context),ua(t.context,Kd))),Are=/*#__PURE__*/ j(2,(e,t)=>Zr(n=>lf(e,cf.forkOrCreate(n.context),t))),uf=function(){return arguments.length===1?e=>df(aa(arguments[0],e)):df(aa(arguments[0],arguments[1]))},df=e=>rf(Pt(Bs(e))),ff=/*#__PURE__*/ df(/*#__PURE__*/ ia()),pf=function(){return arguments.length===1?e=>mf(arguments[0],e):mf(arguments[0],arguments[1])},mf=(e,t)=>hf(yc(t,t=>aa(e,t))),hf=e=>Dre((t,n)=>Jd(e,n)),gf=e=>hf(ac(e,ia())),_f=/*#__PURE__*/ P(`effect/Layer/unwrap`),vf=e=>jre(pf(_f)(e),da(_f)),yf=(e,t,n)=>{let r=Qd(n,`parallel`);return Hl(e,e=>e.build(t,Qd(r,`sequential`)),{concurrency:e.length}).pipe(yc(e=>ate(...e)))},bf=(...e)=>af((t,n)=>yf(e,t,n)),xf=/*#__PURE__*/ j(2,(e,t)=>bf(e,...Array.isArray(t)?t:[t])),Sf=(e,t,n)=>af((r,i)=>_c(Array.isArray(t)?yf(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(Oc(t),yc(e=>n(e,t))))),Cf=/*#__PURE__*/ j(2,(e,t)=>Sf(e,t,M)),wf=/*#__PURE__*/ j(2,(e,t)=>Sf(e,t,(e,t)=>ha(t,e))),jre=/*#__PURE__*/ j(2,(e,t)=>af((n,r)=>_c(e.build(n,r),e=>t(e).build(n,r)))),Mre=e=>rf((t,n)=>e.build(sf(),n)),Tf=Du,Ef=Fu,Df=`~effect/DateTime`,Of=`~effect/DateTime/TimeZone`,kf={[Df]:Df,pipe(){return jt(this,arguments)},[Qn](){return this.toString()},toJSON(){return Ff(this).toJSON()}},Nre={...kf,_tag:`Utc`,[un](){return _n(this.epochMilliseconds)},[kn](e){return jf(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ff(this).toJSON()})`}};({...kf});const Af={[Of]:Of,[Qn](){return this.toString()}};({...Af}),{...Af};const jf=e=>N(e,Df),Pre=e=>e._tag===`Utc`,Mf=e=>{let t=Object.create(Nre);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Nf=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Cd(`Invalid date`);return Mf(t)},Pf=e=>{if(jf(e))return e;if(e instanceof Date)return Nf(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Nf(new Date(e.epochMilliseconds));let t=/* @__PURE__ */ new Date(0);return zre(t,e),Nf(t)}return typeof e==`string`&&!Fre(e)?Nf(/* @__PURE__ */ new Date(e+`Z`)):Nf(new Date(e))},Fre=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Ire=/*#__PURE__*/ Bi(Pf),Lre=e=>Mf(e.epochMilliseconds),Ff=e=>new Date(e.epochMilliseconds),Rre=e=>e.epochMilliseconds,zre=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Bre=e=>Ff(e).toISOString();globalThis.String;const Vre=e=>e.trim(),Hre=(e,t,n)=>{let r=n*(t-e)+e;if(r!==t||e>=t||!Number.isFinite(t))return r;if(t===0)return-Number.MIN_VALUE;let i=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));i.setFloat64(0,t);let a=i.getBigUint64(0);return i.setBigUint64(0,t>0?a-BigInt(1):a+BigInt(1)),i.getFloat64(0)},If=/*#__PURE__*/ j(2,(e,t)=>Nc(e,Ure,e=>t(e))),Lf=e=>e.reasons.some(Rf),Rf=e=>e._tag===`Fail`&&bd(e.error),zf=e=>{let t,n=!1;for(let r of e.reasons)Rf(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?xa(e):n?xa(fd(e.reasons.filter(e=>!Rf(e)))):ba(t)},Ure=e=>{let t=zf(e);return Ca(t)?t:ba(t.success.value)},Bf=e=>{let t=zf(e);return Ca(t)?Od(t.failure):Dd(t.success.value)},Wre=/*#__PURE__*/ j(2,(e,t)=>Rc(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=zf(e);return Ca(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Gre=(e,t,n)=>hl(r=>_c(n?.local?lf(t,sf(),r):Are(t,r),t=>Oc(e,t))),Kre=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>na(t)?Oc(e,t):Gre(e,Array.isArray(t)?bf(...t):t,n)),Vf=`~effect/MutableHashMap`,qre={[Vf]:Vf,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${qn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:$n(Array.from(this))}},[Qn](){return this.toJSON()},pipe(){return jt(this,arguments)}},Jre=()=>{let e=Object.create(qre);return e.backing=/* @__PURE__ */ new Map,e.buckets=/* @__PURE__ */ new Map,e},Hf=/*#__PURE__*/ j(2,(e,t)=>{if(e.backing.has(t))return ji(e.backing.get(t));if(Uf(t))return Ai();let n=dn(t),r=e.buckets.get(n);return r===void 0?Ai():Yre(e,r,t)}),Uf=e=>typeof e!=`object`&&typeof e!=`function`,Yre=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(An(n,t[r])){let n=t[r];return ji(e.backing.get(n))}return Ai()},Xre=/*#__PURE__*/ j(3,(e,t,n)=>{if(e.backing.has(t)||Uf(t))return e.backing.set(t,n),e;let r=dn(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Zre(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Zre=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(An(t,e[n]))return e[n]},Wf=/*#__PURE__*/ j(2,(e,t)=>{if(Uf(t))return e.backing.delete(t),e;let n=dn(t),r=e.buckets.get(n);if(r===void 0)return e;for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i===t||An(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Qre=e=>(e.backing.clear(),e.buckets.clear(),e),$re=e=>e.backing.size,Gf=br,Kf=Bl,qf=Hl,Jf=Vl,Yf=rne,Xf=ine,F=Bs,Zf=Ks,Qf=Ws,I=Us,L=Ys,$f=Zs,ep=Qs,R=sne,z=Hs,tp=Vs,np=tne,rp=qs,ip=nne,eie=Gs,ap=Zr,op=ene,B=_c,tie=yne,sp=pc,cp=mc,lp=Lc,nie=Zne,up=Hc,V=yc,dp=ac,fp=hc,pp=Pc,mp=Gne,rie=Kne,hp=jc,gp=Bne,_p=Fc,iie=zne,vp=Ic,yp=Jne,bp=Une,xp=Vne,Sp=Yne,Cp=Xne,aie=sd,oie=Gc,wp=Uc,sie=rre,Tp=Pu,cie=gne,Ep=gc,lie=Fne,uie=Ine,Dp=Vc,die=_ne,Op=Rc,kp=Bc,Ap=Mne,jp=Dc,Mp=Kre,Np=Oc,fie=Pne,Pp=Ane,Fp=jne,Ip=Tc,Lp=kc,Rp=dl,zp=pl,pie=hl,Bp=gl,Vp=_l,Hp=Sl,Up=wl,Wp=yl,Gp=xl,Kp=kl,qp=Al,Jp=Rl,Yp=El,Xp=jl,Zp=zl,Qp=Lne,mie=Eu,hie=yu,$p=Su,em=Tu,tm=wu,nm=Xl,rm=Ql,im=$l,am=nu,om=eu,sm=au,gie=iu,cm=cu,lm=su,H=$s,um=cne,dm=Nu,fm=/*#__PURE__*/ td(`Fatal`),pm=/*#__PURE__*/ td(`Warn`),mm=/*#__PURE__*/ td(`Error`),hm=/*#__PURE__*/ td(`Info`),gm=/*#__PURE__*/ td(`Debug`),_m=/*#__PURE__*/ j(e=>Gf(e[0]),(e,...t)=>Ec(e,xre,e=>{let n=t.length===1?{...e,...t[0]}:{...e};return t.length===1||or(n,t[0],t[1]),n})),vm=(e,t,n)=>(...r)=>$f(i=>{try{e(...r,(e,n)=>{i(e?t?Qf(()=>z(t(e,r))):z(e):F(n))})}catch(e){i(n?z(n(e,r)):rp(e))}}),ym=bne,bm=xne,xm=Sne,Sm=vne,Cm=Cne,wm=lne,Tm=`~effect/BigDecimal`,Em={[Tm]:Tm,[un](){let e=Pm(this);return mn(vn(String(e.value)),_n(e.scale))},[kn](e){return Dm(e)&&Rm(this,e)===0},toString(){return`BigDecimal(${Bm(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Qn](){return this.toJSON()},pipe(){return jt(this,arguments)}},Dm=e=>N(e,Tm),Om=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(Em);return n.value=e,n.scale=t,n},km=(e,t)=>{let n=Om(e,t);return n.normalized=n,n},Am=/*#__PURE__*/ BigInt(0),jm=/*#__PURE__*/ BigInt(1),Mm=/*#__PURE__*/ BigInt(10),Nm=/*#__PURE__*/ km(Am,0),Pm=e=>{if(e.normalized===void 0){if(e.value===Am)e.normalized=Nm;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=km(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Fm=[jm],Im=(e,t)=>e===t?0:e<t?-1:1,Lm=(e,t)=>{let n=`${e.value<Am?-e.value:e.value}`,r=`${t.value<Am?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Am)return i<Am?-1:1;let a=Math.max(n.length,r.length);return Ci(n.padEnd(a,`0`),r.padEnd(a,`0`))},Rm=(e,t)=>{if(e.scale===t.scale)return Im(e.value,t.value);let n=zm(e),r=zm(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>100)return n===-1?Lm(t,e):Lm(e,t);let o=Fm[a]??=Mm**BigInt(a);return i>0?Im(e.value,t.value*o):Im(e.value*o,t.value)},zm=e=>e.value===Am?0:e.value<Am?-1:1,Bm=e=>{let t=Pm(e);if(Math.abs(t.scale)>=16)return Vm(t);let n=t.value<Am,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},Vm=e=>{if(Hm(e))return`0e+0`;let t=Pm(e),n=`${t.value}`,r=t.value<Am?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Hm=e=>e.value===Am,Um=globalThis.BigInt,Wm=e=>e>Um(2**53-1)||e<Um(-(2**53-1))?Ai():ji(Number(e)),Gm=/*#__PURE__*/ BigInt(0),Km=/*#__PURE__*/ BigInt(1),qm=/*#__PURE__*/ BigInt(1e3),Jm=/*#__PURE__*/ BigInt(1024),Ym=[{symbol:`B`,factor:Km,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:qm,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:qm**/*#__PURE__*/ BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:qm**/*#__PURE__*/ BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:qm**/*#__PURE__*/ BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:qm**/*#__PURE__*/ BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:qm**/*#__PURE__*/ BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:qm**/*#__PURE__*/ BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:qm**/*#__PURE__*/ BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:qm**/*#__PURE__*/ BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:qm**/*#__PURE__*/ BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],Xm=[Ym[0],{symbol:`KiB`,factor:Jm,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:Jm**/*#__PURE__*/ BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:Jm**/*#__PURE__*/ BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:Jm**/*#__PURE__*/ BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:Jm**/*#__PURE__*/ BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:Jm**/*#__PURE__*/ BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:Jm**/*#__PURE__*/ BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:Jm**/*#__PURE__*/ BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}],Zm=[...Ym,.../*#__PURE__*/ Xm.slice(1)],Qm=/*#__PURE__*/ new Map(/*#__PURE__*/ Zm.flatMap(e=>e.names.map(t=>[t,e]))),$m=/*#__PURE__*/ new Map(/*#__PURE__*/ Zm.map(e=>[e.symbol,e])),eh=e=>e,th=/*#__PURE__*/ eh(Gm),nh=e=>{throw Error(`Invalid ByteSize: ${e}`)},rh=e=>!Number.isSafeInteger(e)||e<0?nh(`expected a non-negative safe integer, received ${e}`):eh(BigInt(e)),ih=(e,t)=>{if(typeof e==`bigint`)return e<Gm?nh(`expected a non-negative quantity, received ${e}`):eh(e*t.factor);let n=e*Number(t.factor);return!Number.isSafeInteger(n)||n<0?nh(`expected an exact non-negative safe-integer byte result, received ${e} ${t.symbol}`):eh(BigInt(n))},ah=e=>{let t=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(e);if(t===null)return nh(`unsupported syntax ${JSON.stringify(e)}`);let n=Qm.get(t[3]);if(n===void 0)return nh(`unsupported unit ${JSON.stringify(t[3])}`);let r=t[2]??``,i=BigInt(10)**BigInt(r.length),a=BigInt(t[1]+r)*n.factor;return a%i===Gm?eh(a/i):nh(`${JSON.stringify(e)} does not represent an integral number of bytes`)},oh=e=>{switch(typeof e){case`bigint`:return e<Gm?nh(`expected a non-negative bigint, received ${e}`):eh(e);case`number`:return rh(e);case`string`:return ah(e)}return nh(`unsupported input ${e}`)},sh=/*#__PURE__*/ Bi(oh),ch=e=>typeof e==`bigint`?oh(e):rh(e),lh=/*#__PURE__*/ (e=>t=>ih(t,$m.get(e)))(`MiB`),uh=jf,dh=Pre,fh=Nf,ph=Pf,mh=Ire,hh=Lre,gh=Rre,_h=Bre,vh=e=>xh(typeof e==`string`?Sh.encode(e):e),yh=e=>{let t=wh(e),n=t.length;if(n%4!=0)return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=Dh(t.charCodeAt(e))<<18|Dh(t.charCodeAt(e+1))<<12|Dh(t.charCodeAt(e+2))<<6|Dh(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return ba(r)}catch(e){return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},bh=e=>Ta(yh(e),e=>Ch.decode(e)),xh=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=Th[e[r-2]>>2],n+=Th[(e[r-2]&3)<<4|e[r-1]>>4],n+=Th[(e[r-1]&15)<<2|e[r]>>6],n+=Th[e[r]&63];return r===t+1&&(n+=Th[e[r-2]>>2],n+=Th[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Th[e[r-2]>>2],n+=Th[(e[r-2]&3)<<4|e[r-1]>>4],n+=Th[(e[r-1]&15)<<2],n+=`=`),n},Sh=/*#__PURE__*/ new TextEncoder,Ch=/*#__PURE__*/ new TextDecoder,wh=e=>e.replace(/[\n\r]/g,``),Th=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Eh=/*#__PURE__*/ (/* @__PURE__ */ new Uint8Array(123)).fill(255);for(let e=0;e<64;e++)Eh[/*#__PURE__*/ Th.charCodeAt(e)]=e;Eh[61]=0;const Dh=e=>{if(e>=Eh.length||Eh[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Eh[e]},Oh=`~effect/http/Cookies`,kh=e=>N(e,Oh),Ah=`~effect/http/Cookies/Cookie`,jh=`~effect/http/Cookies/CookieError`;var Mh=class extends zo{},Nh=class e extends (/*#__PURE__*/ Bo(`CookiesError`)){static fromReason(t,n){return new e({reason:new Mh({_tag:t,cause:n})})}[jh]=jh;get message(){return this.reason._tag}};const Ph={[Oh]:Oh,...er,toJSON(){return{_id:`effect/Cookies`,cookies:Ea(this.cookies,e=>e.toJSON())}},pipe(){return jt(this,arguments)}},Fh=e=>{let t=Object.create(Ph);return t.cookies=e,t},Ih=e=>{let t={};for(let n of e)or(t,n.name,n);return Fh(t)},Lh=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=Rh(e.trim());t&&n.push(t)}return Ih(n)};function Rh(e){let t=e.split(`;`).map(e=>e.trim()).filter(e=>e!==``);if(t.length===0)return;let n=t[0].indexOf(`=`);if(n===-1)return;let r=t[0].slice(0,n);if(!Hh.test(r))return;let i=t[0].slice(n+1),a=tg(i);if(t.length===1)return Object.assign(Object.create(Gh),{name:r,value:a,valueEncoded:i});let o={};for(let e=1;e<t.length;e++){let n=t[e],r=n.indexOf(`=`),i=r===-1?n:n.slice(0,r).trim(),a=r===-1?void 0:n.slice(r+1).trim();switch(i.toLowerCase()){case`domain`:{if(a===void 0)break;let e=a.trim().replace(/^\./,``);e&&(o.domain=e);break}case`expires`:{if(a===void 0)break;let e=new Date(a);isNaN(e.getTime())||(o.expires=e);break}case`max-age`:{if(a===void 0)break;let e=parseInt(a,10);isNaN(e)||(o.maxAge=fo(e));break}case`path`:if(a===void 0)break;a[0]===`/`&&(o.path=a);break;case`priority`:if(a===void 0)break;switch(a.toLowerCase()){case`low`:o.priority=`low`;break;case`medium`:o.priority=`medium`;break;case`high`:o.priority=`high`}break;case`httponly`:o.httpOnly=!0;break;case`secure`:o.secure=!0;break;case`partitioned`:o.partitioned=!0;break;case`samesite`:if(a===void 0)break;switch(a.toLowerCase()){case`lax`:o.sameSite=`lax`;break;case`strict`:o.sameSite=`strict`;break;case`none`:o.sameSite=`none`}}}return Object.assign(Object.create(Gh),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}const zh=/*#__PURE__*/ Ih([]),Bh=e=>pte(e.cookies),Vh=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Hh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Uh=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,Wh=/^[\u0020-\u003a\u003c-\u007e]+$/,Gh={[Ah]:Ah,...er,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}};function Kh(e,t,n){let r=encodeURIComponent(t),i=qh(e,r,n);return i===void 0?ba(Object.assign(Object.create(Gh),{name:e,value:t,valueEncoded:r,options:n})):xa(i)}function qh(e,t,n){if(!Hh.test(e))return Nh.fromReason(`InvalidCookieName`);if(t&&!Vh.test(t))return Nh.fromReason(`InvalidCookieValue`);if(n?.domain!==void 0&&!Uh.test(n.domain))return Nh.fromReason(`InvalidCookieDomain`);if(n?.path!==void 0&&!Wh.test(n.path))return Nh.fromReason(`InvalidCookiePath`);if(n?.maxAge!==void 0&&!no(Ja(n.maxAge)))return Nh.fromReason(`CookieInfinityMaxAge`)}const Jh=/*#__PURE__*/ j(2,(e,t)=>Fh({...e.cookies,...t.cookies})),Yh=/*#__PURE__*/ j(e=>kh(e[0]),(e,t,n,r)=>Ta(Kh(t,n,r),n=>Fh(gte(e.cookies,t,n))));function Xh(e){let t=qh(e.name,e.valueEncoded,e.options);if(t!==void 0)throw t;let n=e.name+`=`+e.valueEncoded;if(e.options===void 0)return n;let r=e.options;if(r.maxAge!==void 0){let e=vo(Ja(r.maxAge));n+=`; Max-Age=`+Math.trunc(e)}if(r.domain!==void 0&&(n+=`; Domain=`+r.domain),r.path!==void 0&&(n+=`; Path=`+r.path),r.priority!==void 0)switch(r.priority){case`low`:n+=`; Priority=Low`;break;case`medium`:n+=`; Priority=Medium`;break;case`high`:n+=`; Priority=High`}if(r.expires!==void 0&&(n+=`; Expires=`+r.expires.toUTCString()),r.httpOnly&&(n+=`; HttpOnly`),r.secure&&(n+=`; Secure`),r.partitioned&&(n+=`; Partitioned`),r.sameSite!==void 0)switch(r.sameSite){case`lax`:n+=`; SameSite=Lax`;break;case`strict`:n+=`; SameSite=Strict`;break;case`none`:n+=`; SameSite=None`}return n}const Zh=e=>Object.values(e.cookies).map(e=>`${e.name}=${e.valueEncoded}`).join(`; `),Qh=e=>{let t={},n=Object.values(e.cookies);for(let e=0;e<n.length;e++){let r=n[e];or(t,r.name,r.value)}return t},$h=e=>Object.values(e.cookies).map(Xh);function eg(e){let t={},n=e.length,r=0,i=0;for(;i!==n;){i=e.indexOf(`;`,r),i===-1&&(i=n);let a=e.indexOf(`=`,r);if(a===-1)break;if(a>i){r=i+1;continue}let o=e.substring(r,a++).trim();if(!Object.hasOwn(t,o)){let n=e.charCodeAt(a)===34?e.substring(a+1,i-1).trim():e.substring(a,i).trim();or(t,o,n.indexOf(`%`)===-1?n:tg(n))}r=i+1}return t}const tg=e=>{try{return decodeURIComponent(e)}catch{return e}},ng=/*#__PURE__*/ new WeakMap,rg=e=>{if(ng.has(e))return ng.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},ig=`~effect/Redacted`,ag=e=>N(e,ig),og=(e,t)=>{let n=Object.create(sg);return t?.label&&(n.label=t.label),ng.set(n,e),n},sg={[ig]:{_A:e=>e},label:void 0,...vr,toJSON(){return this.toString()},toString(){return`<redacted${Jt(this.label)?`:`+this.label:``}>`},[un](){return dn(ng.get(this))},[kn](e){return ag(e)&&An(ng.get(this),ng.get(e))}},cg=rg,lg=e=>ai((t,n)=>e(cg(t),cg(n))),ug=/*#__PURE__*/ Symbol.for(`~effect/http/Headers`),dg=/*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null),{[ug]:{value:ug},[Hn]:{value(e){return Sg(this,da(e,wg))}},toJSON:{value(){return Un(this)}},[kn]:{value(e){return pg(this,e)}},[un]:{value(){return bn(this)}},toString:{value:er.toString},[Qn]:{value:er[Qn]}}),fg=e=>Object.assign(Object.create(dg),e),pg=/*#__PURE__*/ vte(/*#__PURE__*/ oi()),mg=/*#__PURE__*/ Object.create(dg),hg=e=>{if(e===void 0)return mg;if(Symbol.iterator in e){let t=Object.create(dg);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(dg);for(let[n,r]of Object.entries(e))Array.isArray(r)?t[n.toLowerCase()]=r.join(`, `):r!==void 0&&(t[n.toLowerCase()]=r);return t},gg=e=>Object.setPrototypeOf(e,dg),_g=/*#__PURE__*/ j(3,(e,t,n)=>{let r=fg(e);return r[t.toLowerCase()]=n,r}),vg=/*#__PURE__*/ j(2,(e,t)=>fg({...e,...hg(t)})),yg=/*#__PURE__*/ j(2,(e,t)=>{let n=fg(e);return Object.assign(n,t),n}),bg=/*#__PURE__*/ j(2,(e,t)=>{let n=fg(e);return delete n[t.toLowerCase()],n}),xg=/*#__PURE__*/ j(2,(e,t)=>{let n=fg(e);for(let e of t)delete n[e.toLowerCase()];return n}),Sg=/*#__PURE__*/ j(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=og(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=og(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),Cg=(e,t)=>{let n=e.toLowerCase();for(let r=0;r<t.length;r++){let i=t[r];if(typeof i==`string`){if(i.toLowerCase()===n)return!0}else if(e.search(i)!==-1)return!0}return!1},wg=/*#__PURE__*/ _a(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Tg=e=>typeof e==`string`?e:cg(e),Eg=`~effect/http/UrlParams`,Dg=e=>N(e,Eg),Og={...vr,[Eg]:Eg,[Symbol.iterator](){return this.params[Symbol.iterator]()},[Hn](e){return{_id:`UrlParams`,params:Object.fromEntries(zg(this,da(e,Yg)))}},toJSON(){return Un(this)},[kn](e){return Ng(this,e)},[un](){return Sn(this.params.flat())}},kg=e=>{let t=Object.create(Og);return t.params=e,t},Ag=e=>{if(Dg(e))return e;let t=jg(e),n=[];for(let e=0;e<t.length;e++)if(Array.isArray(t[e][0])){let[r,i]=t[e];n.push([`${r[0]}[${r.slice(1).join(`][`)}]`,i])}else n.push(t[e]);return kg(n)},jg=e=>{let t=typeof e[Symbol.iterator]==`function`?ka(e):Object.entries(e),n=[];for(let[e,r]of t)if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]!==void 0&&n.push([e,Mg(r[t])]);else if(typeof r==`object`&&r&&!ag(r)){let t=jg(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,Mg(r)]);return n},Mg=e=>ag(e)?e:String(e),Ng=/*#__PURE__*/ ai((e,t)=>Pg(e.params,t.params)),Pg=/*#__PURE__*/ wte(/*#__PURE__*/ ute([/*#__PURE__*/ oi(),/*#__PURE__*/ Tee()])),Fg=/*#__PURE__*/ kg([]),Ig=/*#__PURE__*/ j(2,(e,t)=>{let n=Ag(t).params.slice(),r=/* @__PURE__ */ new Set;for(let e=0;e<n.length;e++)r.add(n[e][0]);for(let t=0;t<e.params.length;t++)r.has(e.params[t][0])||n.push(e.params[t]);return kg(n)}),Lg=e=>new URLSearchParams(Ag(e).params.map(([e,t])=>[e,Tg(t)])).toString(),Rg=e=>{let t={};for(let[n,r]of e.params){let e=Tg(r);if(!Object.hasOwn(t,n))or(t,n,e);else{let r=t[n];typeof r==`string`?or(t,n,[r,e]):r.push(e)}}return t},zg=/*#__PURE__*/ j(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Bg(e,n)?og(t):t])}),Bg=Cg,Vg=(e,t=Jg())=>{e.includes(`@`)&&(e=Gg(e));let n=e.indexOf(`?`);if(n===-1||t.length===0)return e;let r=e.indexOf(`#`);if(r!==-1&&r<n)return e;let i=r===-1?e.length:r;return e.slice(0,n+1)+Kg(e.slice(n+1,i),t)+e.slice(i)},Hg=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,Ug=/[/\\?#]/,Wg=/[/?#]/,Gg=e=>{let t=``,n=[];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===9||i===10||i===13||t===``&&i<=32||(t+=e[r],n.push(r))}let r=Hg.exec(t);if(r===null)return e;let i=r[0].length,a=r[1]!==void 0||!r[0].includes(`:`),o=t.slice(i),s=o.search(a?Ug:Wg),c=(s===-1?o:o.slice(0,s)).lastIndexOf(`@`);return c===-1?e:e.slice(0,n[i])+`REDACTED:REDACTED`+e.slice(n[i+c])},Kg=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Bg(qg(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),qg=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},Jg=()=>da(globalThis[`~effect/Fiber/currentFiber`]?.context??ia(),Yg),Yg=/*#__PURE__*/ _a(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function Xg(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Zg(e){return t=>Xg(t)?.[e]}const Qg=`~structural`,$g=`~identifier`,e_=`~sentinels`,t_=`~constructor`,n_=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],r_=/*#__PURE__*/ Zg(`identifier`),i_=/*#__PURE__*/ Zg($g),a_=/*#__PURE__*/ Zg(`description`),o_=/*#__PURE__*/ Vt(e=>{let t=Xg(e)?.identifier;return typeof t==`string`?t:e.getExpected(o_)}),s_=/*#__PURE__*/ new Set([e_,Qg,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),c_=/*#__PURE__*/ Symbol(),l_=Dd,u_=/*#__PURE__*/ l_(c_),d_=/*#__PURE__*/ l_(c_),f_=e=>e===c_?Ai():ji(e),p_=e=>e._tag===`None`?u_:l_(e.value),m_=`~effect/SchemaIssue/Issue`;function h_(e){return N(e,m_)&&e[m_]===m_}function g_(e){return Object.hasOwn(e,`input`)}var __=class{[m_]=m_;constructor(e,t){t?.reportInput===!0&&e!==c_&&(this.input=e)}};const v_=class extends __{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},y_=class extends __{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},b_=class extends __{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},x_=class extends __{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},S_=class extends __{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},C_=class extends __{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},w_=class extends __{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},T_=class extends __{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function E_(e,t,n,r,i){return new C_(e,[new b_([t],n)],r,i)}const D_=class extends __{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},O_=class extends __{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},k_=class extends __{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function A_(e,t,n){if(h_(e))return e;if(typeof e==`string`)return new T_({message:e},t,n);let r=typeof e.issue==`string`?new T_({message:e.issue},t,n):e.issue;return new b_(e.path,r)}function j_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new T_(void 0,t,n):A_(e,t,n)}function M_(e,t,n,r){return Array.isArray(t)?Na(t)?t.length===1?A_(t[0],n,r):new C_(e,Ia(t,e=>A_(e,n,r)),n,r):void 0:j_(t,n,r)}const N_=e=>{let t=W_(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return R_(o_(e.ast),e);case`InvalidValue`:{let t=L_(e);if(t!==void 0)return R_(t,e);let n=I_(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=I_(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=I_(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},P_=e=>W_(e.issue)??W_(e);function F_(e){return t=>({issues:z_(t,[],e?.leafHook??N_,e?.checkHook??P_)})}function I_(e){return g_(e)?qn(e.input):void 0}function L_(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function R_(e,t){let n=I_(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function z_(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];if(e.issue._tag!==`InvalidValue`)return z_(e.issue,t,n,r);let a=L_(e.issue);return[{path:t,message:a===void 0?R_(B_(e.filter),e):R_(a,e.issue)}]}case`Encoding`:return z_(e.issue,t,n,r);case`Pointer`:return z_(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>z_(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:W_(e)??R_(o_(e.ast),e)}]:e.issues.flatMap(e=>z_(e,t,n,r));default:return[{path:t,message:n(e)}]}}function B_(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>B_(e)).join(` & `)}}function V_(){return e=>U_(e,``)}const H_=/*#__PURE__*/ V_();function U_(e,t){let n;switch(e._tag){case`Filter`:{let r=P_(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return U_(e.issue,t);let r=L_(e.issue);n=r===void 0?R_(B_(e.filter),e):R_(r,e.issue)}break}case`Encoding`:return U_(e.issue,t);case`Pointer`:return U_(e.issue,t+Yn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>U_(e,t)).join(`
|
|
16
|
+
`);n=W_(e)??R_(o_(e.ast),e);break;default:n=N_(e)}return t?`${n}\n at ${t}`:n}function W_(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return W_(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function G_(e){let t;for(let n of e.reasons){if(!dd(n)||!h_(n.error))return;t??=n.error}return t}function K_(e,t){let n=G_(e);if(n===void 0)throw Error(t,{cause:e});return n}const q_=(e,t,n)=>{switch(e._tag){case`Passthrough`:return F(t);case`Transform`:return F(Vi(t,e.transform));case`TransformOptional`:return F(e.transform(t));case`TransformEffect`:return Mi(t)?Zf:ym(e.transform(t.value,n),ji);case`TransformOptionalEffect`:return e.transform(t,n)}},J_=e=>Object.assign(Object.create(Mt),e),Y_=(e,t)=>av((n,r)=>Sm(q_(e,n,r),e=>q_(t,e,r))),X_=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Passthrough`)return t;if(t._tag===`Passthrough`)return e;switch(e._tag){case`Transform`:switch(t._tag){case`Transform`:return nv(n=>t.transform(e.transform(n)));case`TransformOptional`:return iv(n=>t.transform(Vi(n,e.transform)));case`TransformEffect`:return rv((n,r)=>t.transform(e.transform(n),r));case`TransformOptionalEffect`:return Y_(e,t)}case`TransformOptional`:switch(t._tag){case`Transform`:return iv(n=>Vi(e.transform(n),t.transform));case`TransformOptional`:return iv(n=>t.transform(e.transform(n)));case`TransformEffect`:case`TransformOptionalEffect`:return Y_(e,t)}case`TransformEffect`:switch(t._tag){case`Transform`:return rv((n,r)=>ym(e.transform(n,r),t.transform));case`TransformOptional`:case`TransformOptionalEffect`:return Y_(e,t);case`TransformEffect`:return rv((n,r)=>Sm(e.transform(n,r),e=>t.transform(e,r)))}case`TransformOptionalEffect`:return Y_(e,t)}});function Z_(e){return av((t,n)=>z(e(t,n)))}function Q_(e){return Z_((t,n)=>{let r={message:e(t)};return Ni(t)?new D_(r,t.value,n):new D_(r)})}const $_=/*#__PURE__*/ Q_(()=>`Encoding is not supported`),ev=/*#__PURE__*/ J_({_tag:`Passthrough`});function tv(){return ev}function nv(e){return J_({_tag:`Transform`,transform:e})}function rv(e){return J_({_tag:`TransformEffect`,transform:e})}function iv(e){return J_({_tag:`TransformOptional`,transform:e})}function av(e){return J_({_tag:`TransformOptionalEffect`,transform:e})}function ov(e){return av(t=>{let n=Ui(t,tn);return Ni(n)?F(n):ym(e,ji)})}function sv(){return nv(globalThis.String)}function cv(){return nv(globalThis.Number)}function _ie(){return nv(Vre)}function vie(e){return rv((t,n)=>ip({try:()=>JSON.parse(t,e?.reviver),catch:()=>new T_({expected:`a valid JSON string`},t,n)}))}function yie(e){return rv((t,n)=>ip({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new T_({expected:`a JSON-serializable value`},t,n)}))}function bie(e){let t=e?.separator??`,`;return nv(e=>e===``?[]:e.split(t))}function xie(){return nv(vh)}function Sie(){return rv((e,t)=>bm(op(yh(e)),()=>new T_({expected:`a valid Base64 string`},e,t)))}const Cie=class extends Nt{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Cie(this.encode,this.decode)}},lv=`~effect/SchemaTransformation/Transformation`,uv=class extends Nt{[lv]=lv;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new uv(this.encode,this.decode)}};function wie(e){return N(e,lv)&&e[lv]===lv}const dv=e=>wie(e)?e:new uv(e.decode,e.encode);function fv(e){return new uv(rv(e.decode),rv(e.encode))}function pv(e){return new uv(nv(e.decode),nv(e.encode))}function Tie(){return new uv(_ie(),tv())}const Eie=/*#__PURE__*/ new uv(/*#__PURE__*/ tv(),/*#__PURE__*/ tv());function mv(){return Eie}const hv=/*#__PURE__*/ new uv(/*#__PURE__*/ cv(),/*#__PURE__*/ sv()),Die=e=>on(e)&&typeof e.message==`string`,Oie=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:gv(e.cause)}):Error(e.message);return typeof e.name==`string`&&e.name!==`Error`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t},kie=e=>{try{let t=Zn(e);return t===void 0?qn(e):JSON.parse(t)}catch{return qn(e)}},Aie=(e,t,n)=>{let r={name:e.name,message:typeof e.message==`string`?e.message:``};return t?.includeStack&&typeof e.stack==`string`&&(r.stack=e.stack),!t?.excludeCause&&e.cause!==void 0&&(r.cause=n(e.cause)),r},jie=e=>{let t=/* @__PURE__ */ new WeakSet,n=r=>{if(bee(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Aie(r,e,n);return t.delete(r),i}return kie(r)};return n},gv=e=>Die(e)?Oie(e):e,Mie=e=>pv({decode:gv,encode:jie(e)}),_v=/*#__PURE__*/ new uv(/*#__PURE__*/ Sie(),/*#__PURE__*/ xie());function Nie(e){return new uv(vie(e??{}),yie(e))}function vv(e){return t=>t._tag===e}const yv=/*#__PURE__*/ vv(`Declaration`),Pie=/*#__PURE__*/ vv(`Null`),Fie=/*#__PURE__*/ vv(`Undefined`),bv=/*#__PURE__*/ vv(`Void`),Iie=/*#__PURE__*/ vv(`Never`),xv=/*#__PURE__*/ vv(`Literal`),Sv=/*#__PURE__*/ vv(`UniqueSymbol`),Lie=/*#__PURE__*/ vv(`Enum`),Cv=/*#__PURE__*/ vv(`Arrays`),wv=/*#__PURE__*/ vv(`Objects`),Tv=/*#__PURE__*/ vv(`Union`),Ev=/*#__PURE__*/ vv(`Suspend`),Dv=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Ov={},kv=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Av=`~effect/Schema`;var jv=class{[Av]=Av;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}};const Mv=class extends jv{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>t===c_?u_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=Vy(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Mv(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},Nv=/*#__PURE__*/ new class extends jv{_tag=`Null`;getParser(){return Zy(this,null)}getExpected(){return`null`}},Rie=class extends jv{_tag=`Undefined`;getParser(){return Zy(this,void 0)}toCodecJson(){return Ay(this,[Pv])}getExpected(){return`undefined`}},Pv=/*#__PURE__*/ new Dv(Nv,/*#__PURE__*/ new uv(/*#__PURE__*/ nv(()=>void 0),/*#__PURE__*/ nv(()=>null))),Fv=/*#__PURE__*/ new Rie,zie=/*#__PURE__*/ new class extends jv{_tag=`Void`;getParser(){let e=l_(void 0);return t=>t===c_?u_:e}toCodecJson(){return Ay(this,[Pv])}getExpected(){return`void`}},Bie=/*#__PURE__*/ new class extends jv{_tag=`Never`;getParser(){return Qy(this,yee)}getExpected(){return`never`}},Vie=/*#__PURE__*/ new class extends jv{_tag=`Any`;getParser(){return Qy(this,an)}getExpected(){return`any`}},Iv=/*#__PURE__*/ new class extends jv{_tag=`Unknown`;getParser(){return Qy(this,an)}getExpected(){return`unknown`}};function Lv(e){return typeof e==`number`?`parts[${e}]`:e}function Rv(e,t,n){if(n.has(e))return!0;if(e.encoding)throw Error(`TemplateLiteral parts cannot have an encoding at ${Lv(t)}`);let r;switch(e._tag){case`String`:case`Number`:case`BigInt`:r=!0;break;case`Literal`:r=!e.checks;break;case`TemplateLiteral`:{let i=Lv(t);r=!e.checks&&e.parts.every((e,t)=>Rv(e,`${i}.parts[${t}]`,n));break}case`Union`:{let i=Lv(t);r=!e.checks&&e.types.every((e,t)=>Rv(e,`${i}.types[${t}]`,n));break}default:return!1}return r&&n.add(e),r}const Hie=class extends jv{_tag=`TemplateLiteral`;parts;encodedParts;literals;suffixLengths;constructor(e,t,n,r,i){super(t,n,r,i);let a=[],o=[],s=/* @__PURE__ */ new Set;for(let t=0;t<e.length;t++){let n=e[t];if(!Rv(n,t,s))throw Error(`Invalid TemplateLiteral part ${n._tag}`);a.push(n),o.push(n._tag===`Literal`?globalThis.String(n.literal):void 0)}let c=Array(a.length+1);c[a.length]=0;for(let e=a.length-1;e>=0;e--)c[e]=c[e+1]+(o[e]?.length??0);this.parts=e,this.encodedParts=a,this.literals=o,this.suffixLengths=c}getParser(e){let t=new Wv(!1,this.parts.map(nb),[]),n=e(Wy(Vv,t,Uie(this)));return(e,t)=>{if(e===c_)return u_;let r=n(e,t);return r._tag===`Success`?d_:xm(r,{onSuccess:()=>e,onFailure:n=>new C_(this,[n],e,t)})}}getExpected(){return`string`}matchPart(e,t){return $y(this,e,t)===void 0?void 0:e}};function Uie(e){return new uv(rv((t,n)=>{let r=$y(e,t,n);return r?F(r):z(new T_({expected:`a string matching template literal parts`},t,n))}),nv(e=>e.join(``)))}const zv=class extends jv{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${qn(e)}`);this.literal=e}getParser(){return Zy(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Bv(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Bv(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Bv(e){let t=globalThis.String(e.literal);return Ay(e,[new Dv(new zv(t),new uv(nv(()=>e.literal),nv(()=>t)))])}const Vv=/*#__PURE__*/ new class extends jv{_tag=`String`;getParser(){return Qy(this,Jt)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&ab(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Wie=class extends jv{_tag=`Number`;getParser(){return Qy(this,Yt)}matchKey(e,t){return this._match(mae,e,t)}matchPart(e,t){return this._match(rb,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:ab(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Hv(this.checks,`effect/schema/isFinite`)||Hv(this.checks,`effect/schema/isInt`))?this:Ay(this,[nae])}toCodecStringTree(){return this.toCodecJson()===this?Ay(this,[gae]):Ay(this,[_ae])}getExpected(){return`number`}};function Hv(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Hv(e.checks,t))}const Uv=/*#__PURE__*/ new Wie,Gie=/*#__PURE__*/ new class extends jv{_tag=`Boolean`;getParser(){return Qy(this,Xt)}getExpected(){return`boolean`}},Wv=class extends jv{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(Gy(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(Gy(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new S_(n,t[o],i),a=new b_([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return z(new C_(n,[a],t,i))}return e.issues?z(new C_(n,e.issues,t,i)):l_(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:new globalThis.Array(r),issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:Wl(t.concurrency),f=d===1?qie(i,e,0,u):Jie(i,e,{concurrency:d,end:u});if(!f)return c(i);if(vc(f))return Sm(f,()=>c(i));let p=!0;return Qf(()=>p?(p=!1,B(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===c_)return u_;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):z(new w_(n,e,a))}catch(e){return rp(e)}}}_rebuild(e,t,n){let r=Vy(this.elements,e),i=Vy(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Wv(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function Kie(e,t,n,r){if(n._tag===`Failure`)return Kv(e,e.ast,r,n);let i=n===d_?t:n[fr];if(i!==c_)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Gy(t.ast))return;let n=new b_([r],new x_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return kd(new C_(e.ast,[n],e.input,e.options))}}const Gv={onItem(e,t,n){let r=n<e.len?t:c_;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Kie},qie=/*#__PURE__*/ Gl()(Gv),Jie=/*#__PURE__*/ ql()(Gv),Kv=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=G_(r.cause);if(i===void 0)return Od(gd(r.cause,r=>new C_(t,[new b_([n],r)],e.input,e.options)));let a=new b_([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return kd(new C_(t,[a],e.input,e.options))},qv=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function Jv(e,t,n=Ov){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(eb(Jy(t)))}const Yv=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Xv(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(Xv);default:return!1}}function Zv(e){let t=My(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(Zv);default:return!1}}function Yie(e){return Xv(e)&&Zv(e)}const Qv=class{parameter;type;constructor(e,t){if(!Yie(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Gy(t)&&!Xy(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},$v=class extends jv{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return Qy(n,vee);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(eb(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return Kv(t,n,i,s)??Md;let c=s===d_?o:s[fr];if(a!==c_&&c!==c_){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Md;or(t.out,a,c)}return Md},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!vc(t))return B(up(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Kv(e,n,r,a)??Md;let o=a===d_?r:a[fr],s=e.input[r],l=i.parserValue(s,e.options);return vc(l)?t(e,r,o,s,l):B(up(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return vc(a)?t(e,n,n,i,a):B(up(a),r=>t(e,n,n,i,r))},u=i?ql()({onItem:(e,[t,n])=>n.is.parameter===Vv?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return wm(function*(t,d){if(t===c_)return c_;if(typeof t!=`object`||!t||Array.isArray(t))return yield*z(new w_(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},h=d.errors===`all`,g=d.onExcessProperty===`error`,_=d.concurrency===void 0?1:Wl(d.concurrency),v=i&&g?n.indexSignatures.map(e=>Jv(f,e.parameter,d)):void 0;if(g){let r=v?new Set(e):e;if(v)for(let e of v)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new S_(n,f[a],d),r=new b_([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*z(new C_(n,[r],t,d))}}}if(r){let e=_===1?ny(m,a):Xie(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Vv?l:c,r=v?.[e]??(t.is.parameter===Vv?Object.keys(f):Jv(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!vc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Pa();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===Vv?Object.keys(f):Jv(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:_});t&&(yield*t)}return m.issues?yield*z(new C_(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return B(up(n),n=>{let i=ey(e,r,n);if(i)return i;let o=()=>l_(e.out),s=ny(e,a.slice(t+1));return s?Sm(s,o):o()})};return(e,t)=>{if(e===c_)return u_;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Wl(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return z(new w_(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=my(i,s),l=c?i[s]:c_,d=n.parser(l,t);if(!vc(d))return u(o,e,d);if(d===d_){c&&or(a,s,l);continue}let f=ey(o,n,d);if(f)return f}}catch(e){return rp(e)}return l_(a)}}_rebuild(e,t,n,r){let i=Vy(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new Yv(t.name,n)}),a=Vy(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new Qv(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new $v(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function ey(e,t,n){if(n._tag===`Failure`)return Kv(e,e.ast,t.name,n);if(n===d_)return;let r=n[fr];if(r!==c_)or(e.out,t.name,r);else if(delete e.out[t.name],!Gy(t.type)){let n=new b_([t.name],new x_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return kd(new C_(e.ast,[n],e.input,e.options))}}const ty={onItem(e,t){if(!my(e.input,t.name))return t.parser(c_,e.options);let n=e.input[t.name];return or(e.out,t.name,n),t.parser(n,e.options)},step:ey},ny=/*#__PURE__*/ Gl()(ty),Xie=/*#__PURE__*/ ql()(ty);function ry(e,t){return e?t?[...e,...t]:e:t}function iy(e,t,n){return new $v(Reflect.ownKeys(e).map(t=>new Yv(t,e[t].ast)),[],n,t)}function ay(e){return e.ast}function oy(e,t=void 0){return new Wv(!1,e.map(e=>e.ast),[],void 0,t)}function sy(e,t,n){return new hy(e.map(ay),t,void 0,n)}function Zie(e,t){if(e.encoding||t.some(e=>e.encoding))throw Error(`StructWithRest does not support encodings`);let n=e.propertySignatures,r=e.indexSignatures,i=e.checks;for(let e of t){for(let t of e.propertySignatures)if(n.some(e=>e.name===t.name))throw Error(`Duplicate identifier: ${JSON.stringify(t.name)}. ts(2300)`);n=n.concat(e.propertySignatures),r=r.concat(e.indexSignatures),i=ry(i,e.checks)}return new $v(n,r,void 0,i)}const cy=/*#__PURE__*/ Ht(e=>{for(;;){if(Ev(e))return Iv;let t=e.encoding;if(!t)return e.recur?.(cy,M)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==M))return Iv;e=t[t.length-1].to}});function ly(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(ly)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function uy(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[e_];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Gy(t)){if(xv(t))return[{key:e.name,literal:t.literal}];if(Sv(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Gy(e)){if(xv(e))return[{key:t,literal:e.literal}];if(Sv(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>uy(cy(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return uy(e.thunk())}}const dy=/*#__PURE__*/ new WeakMap,fy=/*#__PURE__*/ Object.freeze([]),py=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,my=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Qie(e){let t=dy.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=cy(c);if(Iie(l))continue;if(xv(l)||Sv(l)){a??=/* @__PURE__ */ new Map;let e=xv(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=uy(l);if(u.length){n??=/* @__PURE__ */ new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[/* @__PURE__ */ new Map,/* @__PURE__ */ new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=/* @__PURE__ */ new Set),a.add(t)}}else{i??={};let e=ly(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??fy);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??fy;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=/* @__PURE__ */ new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(cn(e)){let n=my(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??fy;if(t)return o}return fy}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=py(t);if(!cn(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=my(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=my(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=my(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(py(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return dy.set(e,t),t}const hy=class extends jv{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===c_)return u_;let i=(o??=Qie(n.types))(e,r);if(i.length===0)return z(new O_(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:vc(r)?gy(n,r.cause,e,t):$ie(n,r,e,t)}return _y(n,a,i,e,t)}}_rebuild(e,t,n){let r=Vy(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new hy(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=Jy(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(xv);if(t.length>0)return`${by(n.isMutable)}[ ${t.map(t=>e(t)+xy(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>xv(e.type));if(t.length>0)return`{ ${t.map(t=>`${by(t.type.context?.isMutable)}${Jn(t.name)}${xy(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function gy(e,t,n,r){let i=G_(t);return i?kd(new O_(e,[i],n,r)):Od(t)}function $ie(e,t,n,r){return hp(t,t=>gy(e,t,n,r))}function _y(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=eae(a,n);if(!o)return a.out?a.out:z(new O_(e,a.issues??[],r,i));if(vc(o))return vy(o,a);let s=!0;return Qf(()=>s?(s=!1,vy(o,a)):_y(e,t,n,r,i))}function vy(e,t){return Sm(e,e=>t.out===d_?F(t.input):t.out?t.out:z(new O_(t.ast,t.issues??[],t.input,t.options)))}const eae=/*#__PURE__*/ Gl()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=G_(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),kd(new k_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Md}}}),yy=/*#__PURE__*/ new hy([/*#__PURE__*/ new zv(`Infinity`),/*#__PURE__*/ new zv(`-Infinity`),/*#__PURE__*/ new zv(`NaN`)]);function by(e){return e?``:`readonly `}function xy(e){return e?`?`:``}const Sy=class extends Nt{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new Sy(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Sy(this.run,this.annotations,!0)}and(e,t){return new Cy([this,e],t)}},Cy=class extends Nt{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Cy(this.checks,{...this.annotations,...e})}and(e,t){return new Cy([this,e],t)}};function wy(e,t,n=!1){return new Sy((t,n,r)=>M_(n,e(t,n,r),t,r),t,n)}function tae(e){return wy(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}const Ty=/*#__PURE__*/ Fy(Uv,[/*#__PURE__*/ tae()]),nae=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([Ty,yy]),/*#__PURE__*/ new uv(/*#__PURE__*/ cv(),/*#__PURE__*/ nv(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Ey(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return wy(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}const Dy=/*#__PURE__*/ new WeakMap;function Oy(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Dy.set(n,ky(e)),n}function ky(e){let t=Dy.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Dy.set(e,n),n}function Ay(e,t){return e.encoding===t?e:Oy(e,{encoding:t})}function jy(e,t){if(e.context===t)return e;let n=ky(e);return n.context===t&&n.encoding===e.encoding?n:Oy(e,{context:t})}function My(e){return e.encoding?My(e.encoding[e.encoding.length-1].to):e}function Ny(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Py(e,ja(e.checks.slice(0,-1),n.annotate(t)))}return Oy(e,{annotations:{...e.annotations,...t}})}function Py(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Oy(e,{checks:t})}function Fy(e,t){return Py(e,ry(e.checks,t))}function Iy(e,t){let n=t(e.to);return n===e.to?e:new Dv(n,e.transformation)}function Ly(e,t){let n=e,r=n[n.length-1],i=Iy(r,t);return i===r?e:ja(e.slice(0,e.length-1),i)}function Ry(e){return t=>t.encoding?Ay(t,Ly(t.encoding,e)):t}function zy(e,t){return Ry(e=>jy(e,t))(e)}function rae(e){function t(n){return n.encoding?Ay(n,Ly(n.encoding,t)):e(n)}return Vt(t)}function By(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:Ay(r,Ly(r.encoding,n))}return e(r)}return Ht(n)}function iae(e,t,n){let r=new Dv(e,t);return Ay(n,n.encoding?[...n.encoding,r]:[r])}function Vy(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function Hy(e,t){return jy(e,e.context?new kv(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new kv(!1,!1,void 0,t))}const Uy=/*#__PURE__*/ Ht(e=>{let t=e.context?e.context.isOptional===!1?new kv(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new kv(!0,!1);return aae(jy(e,t))}),aae=/*#__PURE__*/ Ry(Uy),oae=/*#__PURE__*/ Vt(e=>Uy(new hy([e,Fv])));function sae(e,t){return jy(e,e.context?new kv(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new kv(!1,!1,t))}function Wy(e,t,n){return iae(e,n,t)}function cae(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:Qt(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function lae(e,t){let{literals:n,parameters:r}=cae(e);return new $v(n.map(e=>new Yv(e,t)),r.map(e=>new Qv(e,t)))}function Gy(e){return e.context?.isOptional??!1}function uae(e){return e.context?.isMutable??!1}function Ky(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(Ky)}function dae(e){function t(e){return Ky(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Ma(n)?n:void 0}function fae(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Ev(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}const qy=/*#__PURE__*/ Ht(e=>{let t=ky(e);if(t!==e){let n=qy(t);return n===t&&e.encoding===void 0?e:jy(n,e.context)}let n=`recur`in e?e.recur(qy):e;if(`encodingChecks`in n&&n.encodingChecks){let t=fae(e)?n.encodingChecks:Cv(n)||wv(n)||yv(n)&&n.typeParameters.length>0?dae(n.encodingChecks):void 0;return Oy(n,{encodingChecks:void 0,checks:ry(n.checks,t)})}return n}),Jy=/*#__PURE__*/ Ht(e=>qy(Yy(e)));function pae(e,t){let n=t,r=n.length,i=n[r-1],a=[new Dv(Yy(Ay(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Dv(Yy(n[e-1].to),n[e].transformation.flip()));let o=Yy(i.to);return o.encoding?Ay(o,[...o.encoding,...a]):Ay(o,a)}const Yy=/*#__PURE__*/ Vt(e=>{if(e.encoding)return pae(e,e.encoding);let t=ky(e);if(t!==e){let n=Yy(t);return n===t?e:jy(n,e.context)}return`flip`in e?e.flip(Yy):`recur`in e?e.recur(Yy):e});function Xy(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(Xy);default:return!1}}function Zy(e,t){let n=t===0?d_:l_(t);return(r,i)=>r===c_?u_:r===t?n:z(new w_(e,r,i))}function Qy(e,t){return(n,r)=>n===c_?u_:t(n)?d_:z(new w_(e,n,r))}function $y(e,t,n){let r=e.encodedParts,i=e.literals,a=t.length;for(let e=0;e<i.length;e++){let n=i[e];if(n&&!t.includes(n))return}if(e.suffixLengths[0]>a)return;let o=Array(r.length),s;function c(l,u){if(l===r.length)return u===a;if(s?.has(l*(a+1)+u))return!1;let d=r[l];if(l===r.length-1){let e=t.slice(u);if(d.matchPart(e,n)!==void 0)return o[l]=e,!0}else if(d._tag===`Literal`){let e=i[l];if(t.startsWith(e,u)&&c(l+1,u+e.length))return o[l]=e,!0}else{let r=a-e.suffixLengths[l+1],s=i[l+1],f=s===void 0?r:t.lastIndexOf(s,r);for(;f>=u;){let e=t.slice(u,f);if(d.matchPart(e,n)!==void 0&&c(l+1,f))return o[l]=e,!0;if(f===0)break;f=s===void 0?f-1:t.lastIndexOf(s,f-1)}}return s??=/* @__PURE__ */ new Set,s.add(l*(a+1)+u),!1}return c(0,0)?o:void 0}const eb=/*#__PURE__*/ By(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(eb)}}),tb=/*#__PURE__*/ By(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(tb)}}),nb=/*#__PURE__*/ By(e=>{switch(e._tag){default:return e;case`Number`:case`Literal`:case`BigInt`:return e.toCodecStringTree();case`Union`:return e.recur(nb)}}),rb=/*#__PURE__*/ new globalThis.RegExp(`^${qv}$`),mae=/*#__PURE__*/ new globalThis.RegExp(`^(?:${qv}|Infinity|-Infinity|NaN)$`);function hae(e){return Ey(rb,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:rb.source}),...e})}const ib=/*#__PURE__*/ Fy(Vv,[/*#__PURE__*/ hae()]),gae=/*#__PURE__*/ new Dv(ib,hv),_ae=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([ib,yy]),hv);function ab(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=ab(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new v_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function vae(e){if(!yv(e))return;let t=e.annotations?.[t_];return $t(t)?t(e.typeParameters):void 0}const ob=Zg,sb=r_,yae=a_;function bae(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function xae(e){return e===void 0||typeof e==`string`}function cb(e,t){let n=/* @__PURE__ */ new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function lb(e){return cb(e,bae)}const ub=/*#__PURE__*/ new Mv([],()=>(e,t,n)=>lb(e)?d_:z(new w_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>fb}),db=/*#__PURE__*/ new Dv(ub,/*#__PURE__*/ mv()),Sae=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([/*#__PURE__*/ new Wv(!1,[],[ub]),/*#__PURE__*/ new $v([],[/*#__PURE__*/ new Qv(Vv,ub)])]),/*#__PURE__*/ mv());function Cae(e){return cb(e,xae)}const fb=/*#__PURE__*/ new Dv(/* @__PURE__ */ new Mv([],()=>(e,t,n)=>Cae(e)?d_:z(new w_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),/*#__PURE__*/ mv()),pb=(e,t,n)=>e===d_?n(t):Sm(e,n);function mb(e){if(e._tag===`Middleware`)return(t,n,r)=>{let i=t===d_?e.decode(l_(f_(n)),r):e.decode(ym(t,f_),r);return hb(i)};let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===d_?l_(t):e;case`Transform`:{let e=e=>e===c_?u_:l_(t.transform(e));return(t,n)=>pb(t,n,e)}case`TransformOptional`:{let e=e=>p_(t.transform(f_(e)));return(t,n)=>pb(t,n,e)}case`TransformEffect`:return(e,n,r)=>pb(e,n,e=>e===c_?u_:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>pb(e,n,e=>hb(t.transform(f_(e),r)))}}const hb=e=>Sm(e,p_),gb=(e,t,n,r)=>hp(r,r=>np(()=>gd(r,r=>new y_(e,r,t,n))));function wae(e,t){let n=mb(e.link.transformation),r;return(i,a)=>{if(i===c_)return u_;if(e.isConstructed(i))return d_;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function Tae(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==c_&&r!==void 0)return t(r,i);let a=n;if(vc(a)&&a._tag===`Success`){let e=t(a[fr],i);return e===d_?a:e}return Sm(gb(e,r,i,a),e=>{let n=t(e,i);return n===d_?l_(e):n})}}function Eae(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:Tae(e,n)}function _b(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?vae(e):void 0,o=a?wae(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>mb(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(vc(r)){if(r._tag===`Success`){let i=r===d_?t:r[fr];if(t!==c_&&i!==c_){let i=ab(u,t,void 0,e,n);i&&(r=z(new C_(e,i,t,n)))}}}else r=B(r,r=>{if(t!==c_&&r!==c_){let r=ab(u,t,void 0,e,n);if(r)return z(new C_(e,r,t,n))}return F(r)})}if(s&&!n.disableChecks){if(vc(r)){if(r._tag===`Success`){let i=r===d_?t:r[fr];if(i===c_)return r;let a=ab(s,i,void 0,e,n);a&&(r=z(new C_(e,a,i,n)))}}else r=B(r,t=>{if(t!==c_){let r=ab(s,t,void 0,e,n);if(r)return z(new C_(e,r,t,n))}return F(t)})}return r},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[fr],o=t(a,r)):o=Sm(o,e=>{let n=t(e,r);return n===d_?l_(e):n})}if(o._tag===`Success`){let e=o[fr],t=p(e,r);return t===d_?o:t}return o=gb(e,n,r,o),Sm(o,e=>{let t=p(e,r);return t===d_?l_(e):t})}:p}const Dae=/*#__PURE__*/ Symbol(),vb=/*#__PURE__*/ new WeakMap,Oae=e=>bb(e).parser,yb=e=>bb(e).makeEffect,kae=e=>Eae(e,yb);var Aae=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=_b(this.ast,Oae)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=_b(this.ast,yb,kae)}};function bb(e){let t=vb.get(e);if(t!==void 0)return t;let n=new Aae(e);return vb.set(e,n),n}function xb(e){let t=e.ast,n;return(e,r)=>(n??=Ab(Vae,qy(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Sb(e){let t=xb(e);return(e,n)=>{let r=lm(t(e,n));return Nd(r)?ji(r.value):(K_(r.cause,`Option adapter can only return none for schema issues`),Ai())}}function Cb(e){return zae(qy(e.ast))}function jae(e){return wb(e.ast)}function Mae(e){{let t=jb(kb(e));return e=>{let n=t(e,Ov);return Nd(n)?!0:(K_(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function wb(e){let t=qy(e),n=e=>(n=Mae(t),n(e));return e=>n(e)}function Tb(e,t){let n=kb(e.ast);return t===void 0?n:(e,r)=>n(e,Db(t,r))}function Nae(e,t){return Iae(Tb(e,t))}function Pae(e,t){return Lae(Tb(e,t))}function Eb(e,t){let n=kb(Yy(e.ast));return t===void 0?n:(e,r)=>n(e,Db(t,r))}const Db=(e,t)=>t?{...e,...t}:e,Ob=e=>e===c_?z(new T_):F(e);function kb(e){return Ab(Bae,e)}function Fae(e,t){return e===d_?F(t):vc(e)?e[`~effect/Effect/args`]===c_?Ob(c_):e:Sm(e,Ob)}function Ab(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Ov);return a===d_?F(r):vc(a)?a[`~effect/Effect/args`]===c_?Ob(c_):a:Sm(a,Ob)}}function jb(e){return(t,n)=>lm(e(t,n))}function Iae(e){let t=jb(e);return(e,n)=>{let r=t(e,n);return Nd(r)?ji(r.value):(K_(r.cause,`Option adapter can only return none for schema issues`),Ai())}}function Lae(e){let t=jb(e);return(e,n)=>{let r=t(e,n);return Nd(r)?ba(r.value):xa(K_(r.cause,`Result adapter can only return schema issues`))}}function Rae(e,t){let n=lm(e);if(Nd(n))return n.value;let r=K_(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function zae(e){let t,n;return(r,i)=>{t??=bb(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Ov,o=t.make;if(o!==void 0&&r!==c_){let e;try{e=o(r,a)}catch(e){throw K_(pd(e),`Constructor adapter can only throw schema issues`),e}if(e!==Dae&&e!==c_)return e}return Rae(Fae((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}const Bae=e=>bb(e).parser,Vae=e=>bb(e).makeEffect,Mb=`~effect/Schema/Schema`,Nb=/*#__PURE__*/ Symbol(),Hae={[Mb]:Mb,get make(){let e=Cb(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=xb(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Sb(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return jt(this,arguments)},annotate(e){return this.rebuild(Ny(this.ast,e))},annotateKey(e){return this.rebuild(Hy(this.ast,e))},check(...e){return this.rebuild(Fy(this.ast,e))},rebuild(e){return Pb(e,this[Nb])}};function Pb(e,t){function n(){}let r=Object.setPrototypeOf(n,Hae);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[Nb]=t,r.ast=e,r}function Uae(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Fb(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Ib(e){return encodeURI(Uae(e)).replace(/#/g,`%23`)}function Lb(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function Rb(e){let t=Lb(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(Fb)}function Wae(e){return e.reduce((e,t)=>`${e}/${Ib(t)}`,`#`)}const Gae=[`example`,`discriminator`,`xml`,`externalDocs`];function Kae(e){let t=Object.keys(e.definitions),n=/* @__PURE__ */ new Map,r=new Set(t.filter(e=>zb.test(e))),i=t.filter(e=>!zb.test(e)).sort().map(e=>[e,qae(e)]);for(let[e,t]of i)r.has(t)||(r.add(t),n.set(e,t));for(let[e,t]of i){if(n.has(e))continue;let i,a=0;do i=`${t}_${++a}`;while(r.has(i));r.add(i),n.set(e,i)}function a(t,r=!1){let i=Hb(t.$id),a=on(t.$defs)?t.$defs:void 0;return Bb(t,(t,o)=>{Xae(t,Gae,`OpenAPI 3.1`,`Draft 2020-12`),Vb(t,(t,s)=>{let c=t.startsWith(`#`)?Rb(t):void 0;if(c===void 0||c[0]!==`$defs`||c.length<2)return t;let l=c[1];return i?(r&&!o&&Object.hasOwn(e.definitions,l)&&(a===void 0||!Object.hasOwn(a,l))&&Wb(s,`OpenAPI 3.1`,`a schema resource cannot reference the shared definitions pool`),t):o?t:Wae([`components`,`schemas`,n.get(l)??l,...c.slice(2)])})})}let o=e.schemas.map(e=>a(e,!0)),s={};for(let r of t)or(s,n.get(r)??r,a(e.definitions[r]));return{dialect:`openapi-3.1`,schemas:o,definitions:s}}const zb=/^[a-zA-Z0-9.\-_]+$/;function qae(e){return e.length===0?`_`:e.replace(/[^a-zA-Z0-9._-]/gu,`_`)}function Bb(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!on(e))return e;let a=r||!i&&Hb(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=Yae(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}or(o,t,i)}return t(o,a),o}}function Jae(e,t){return Bb(e,e=>{Vb(e,t)})}function Vb(e,t){typeof e.$ref==`string`&&or(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&or(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function Yae(e,t){if(!on(e))return;let n={};for(let r of Object.keys(e))or(n,r,t(e[r],r));return n}function Hb(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}const Ub=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Ub],[...Ub];function Wb(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Xae(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Wb(i,n,`it is not active in ${r} but would become active in the target`)}function Zae(e){return Pb(Gb(e.ast),{schema:e})}const Gb=/*#__PURE__*/ By(e=>{let t=$ae(e,Gb),n=e.context;return t===e||n===void 0?t:zy(t,Kb(n))});function Kb(e){return e.constructorDefault===void 0?e:new kv(e.isOptional,e.isMutable,void 0,e.annotations)}function qb(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Jb(e){return t=>{let n=[...t].sort((t,n)=>e(Jy(t))-e(Jy(n)));return n.some((e,n)=>e!==t[n])?n:t}}const Qae=/*#__PURE__*/ Jb(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function $ae(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!$t(n))return Ay(e,[db]);let r=n(e.typeParameters.map(e=>Pb(Jy(e))));return r===void 0?e:Ay(e,[Iy(r,t)])}case`Unknown`:return Ay(e,[db]);case`ObjectKeyword`:return Ay(e,[Sae]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return qb(e),e.recur(t,tb);case`Union`:{let n=Qae(e.types);return n===e.types?e.recur(t):new hy(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}function eoe(e){return Pb(Zb(e.ast),{schema:e})}function toe(e){return Pb($b(e.ast))}const noe=/*#__PURE__*/ Jb(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function roe(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>Pb(t(Jy(e)))),i=e.annotations?.toCodecStringTree;if($t(i)){let n=i(r);return n===void 0?e:Ay(e,[Iy(n,t)])}let a=e.annotations?.toCodecJson,o=$t(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??($t(s)?s(r):void 0);return c===void 0?n(e):Ay(e,[Iy(c,t)])}case`Null`:return Ay(e,[ioe]);case`Boolean`:return Ay(e,[aoe]);case`Unknown`:case`ObjectKeyword`:return Ay(e,[fb]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return qb(e),e.recur(t,tb);case`Union`:{let n=noe(e.types);return n===e.types?e.recur(t):new hy(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}const ioe=/*#__PURE__*/ new Dv(/*#__PURE__*/ new zv(`null`),/*#__PURE__*/ new uv(/*#__PURE__*/ nv(()=>null),/*#__PURE__*/ nv(()=>`null`))),aoe=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([/*#__PURE__*/ new zv(`true`),/*#__PURE__*/ new zv(`false`)]),/*#__PURE__*/ new uv(/*#__PURE__*/ nv(e=>e===`true`),/*#__PURE__*/ sv())),Yb=/*#__PURE__*/ new uv(/*#__PURE__*/ nv(e=>typeof e==`string`?[e]:e),/*#__PURE__*/ tv()),Xb=e=>e.transformation===Yb,Zb=/*#__PURE__*/ By(e=>{let t=roe(e,Zb,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?zy(t,Kb(e.context)):t},{stopAt:Xb}),Qb=e=>Gy(e)?Uy(Iv):Iv,$b=/*#__PURE__*/ By(e=>{let t=ooe(e);if(Cv(t)){let n=Wy(new hy([new Wv(t.isMutable,t.elements.map(Qb),t.rest.map(Qb)),Vv],{mode:`anyOf`}),t,Yb);return Gy(e)?Uy(n):n}return t},{stopAt:Xb});function ooe(e){return e._tag===`Declaration`||e._tag===`Arrays`||e._tag===`Objects`||e._tag===`Union`||e._tag===`Suspend`?e.recur($b):e}globalThis.RegExp;const soe=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function ex(e,t){return t.length>0&&(e+=`\n at ${Yn(t)}`),Error(e)}function tx(e){return`#/$defs/${Ib(e)}`}const coe=/*#__PURE__*/ new Set([...s_,$g,...n_]);function nx(e,t){if(e===void 0)return;let n={},r=e.title;typeof r==`string`&&(n.title=r);let i=e.description,a=e.expected;typeof i==`string`?n.description=i:t?.generateDescriptions===!0&&typeof a==`string`&&(n.description=a);let o=e.default;lb(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&lb(s)&&(n.examples=s);let c=e.readOnly;typeof c==`boolean`&&(n.readOnly=c);let l=e.writeOnly;typeof l==`boolean`&&(n.writeOnly=l);let u=e.format;typeof u==`string`&&(n.format=u);let d=e.contentEncoding;typeof d==`string`&&(n.contentEncoding=d);let f=e.contentMediaType;typeof f==`string`&&(n.contentMediaType=f);let p=e.contentSchema;if(lb(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!coe.has(r)&&t.includeAnnotationKey(r)&&lb(i)&&or(n,r,i);return Object.keys(n).length===0?void 0:n}function rx(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=rx(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function loe(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}function ix(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function uoe(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}function doe(e,t,n){if(typeof e.$ref==`string`)return;let r={...e,...t};for(let i of n){if(!Object.hasOwn(e,i))continue;let n=e[i],a=t[i];if(typeof n!=`number`||typeof a!=`number`)return;if(`|minimum|exclusiveMinimum|minLength|minItems|minProperties|`.includes(`|${i}|`))r[i]=Math.max(n,a);else if(`|maximum|exclusiveMaximum|maxLength|maxItems|maxProperties|`.includes(`|${i}|`))r[i]=Math.min(n,a);else return}return typeof r.minimum==`number`&&typeof r.exclusiveMinimum==`number`&&delete r[r.exclusiveMinimum>=r.minimum?`minimum`:`exclusiveMinimum`],typeof r.maximum==`number`&&typeof r.exclusiveMaximum==`number`&&delete r[r.exclusiveMaximum<=r.maximum?`maximum`:`exclusiveMaximum`],r}const ax=`|title|description|default|examples|readOnly|writeOnly|`;function ox(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=loe(e);if(i!==void 0||a){let r=rx(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:ix(r.schema,ax)&&uoe(o,s)?{...o,...r.schema}:ox(o,r.schema,n)}}if(n){let n=doe(e,t,r);if(n!==void 0)return n}let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function sx(e,t=/* @__PURE__ */ new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>sx(e,t)))}function foe(e){return Array.isArray(e)}function cx(e,t,n,r){let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new WeakMap,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=Ia(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!sx(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=g(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>An(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Ia(u,h),f={};for(let e of l)a.has(e)||or(f,e,h(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw ex(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=v(n[e],[`references`,e],a[1]),a}function h(e){return Jae(e,e=>{let t=Lb(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(Fb(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,tx(r))})}function g(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[$g]:void 0}function _(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>v(e,[...n,`representation`,`schemas`,t],i))??[]}),c=foe(s);c&&i.push(!1);let l=c?s[0]:s,u=nx(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`:`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames||title|description|default|examples|readOnly|writeOnly|`;return[d,e._tag===`Filter`&&ix(d,f)&&(u===void 0||ix(u,ax))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=_(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=nx(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function v(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:tx(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=y(e,t,a),c=nx(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&poe(s.type)?s.type:void 0,i=_(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=ox(s,...i))}return o.set(e,[s,a]),p(s)}function y(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return v(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw ex(`Invalid numeric enum value ${globalThis.String(n)}`,[...t,`enums`,r,1]);return{type:typeof n,enum:[n],title:e}});return n.length===0?{not:{}}:{anyOf:n}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(lx).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw ex(`Invalid schema representation document`,[...t,`rest`]);let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=v(e.type,[...t,`elements`,i,`type`],n),s=nx(e.annotations,r);return s===void 0?o:p(ox(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=v(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw ex(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=v(s.type,[...t,`propertySignatures`,i,`type`],n),u=nx(s.annotations,r);or(a,c,u===void 0?l:p(ox(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=v(i.type,[...t,`indexSignatures`,r,`type`],n);An(a,{not:{}})&&(a=!1),l.push(a);let o=b(i.parameter,[...t,`indexSignatures`,r,`parameter`],/* @__PURE__ */ new Set);if(o===void 0)u=!0,n.push(!1);else if(o.length===0)c.push(a);else for(let e of o){let t=s[e];or(s,e,t===void 0?a:t===!1||a===!1?!1:p(ox(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(v(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>v(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=moe(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function b(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw ex(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return b(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=v(e,t,n);return sx(n)&&r.type===`string`&&typeof r.pattern==`string`&&ix(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(lx).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=b(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw ex(`Invalid schema representation document`,t)}}}function poe(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function moe(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function lx(e){switch(e._tag){case`Literal`:return soe(globalThis.String(e.literal));case`String`:return`[\\s\\S]*?`;case`Number`:return qv;case`TemplateLiteral`:return e.parts.map(lx).join(``);case`Union`:return`(?:${e.types.map(lx).join(`|`)})`;default:throw ex(`Invalid schema representation document`,[])}}function hoe(e,t){let n=cx([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}function goe(e,t){return cx(e.representations,e.representations.map((e,t)=>[`representations`,t]),e.references,t)}const _oe=({identifier:e})=>e;function ux(e){return e===void 0?void 0:{annotations:e}}function voe(e,t){let{references:n,representations:r}=dx([e],t);return{representation:r[0],references:n}}function dx(e,t){let n={},r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set;for(let t of e)f(t);let s=t?.referencePolicy??_oe;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:Ia(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:Ny(e,{identifier:n}):i_(e)===r?e:Ny(e,{[$g]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),or(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=My(e),n=ky(t),r=r_(t),i=r===void 0?(t===e?void 0:r_(e))??i_(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=/* @__PURE__ */ new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t))t.isRecursive=!0;else if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(qy(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?h(n):u(r,t.identifier===void 0?n:l(n,t,r))}function h(e){let t=g(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...v(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...ux(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...ux(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...ux(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...ux(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...ux(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=My(e),n=t.context?.annotations;return{isOptional:Gy(t),type:m(e),...ux(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...ux(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=My(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Gy(t),isMutable:uae(t),...ux(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...ux(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...ux(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...ux(e.annotations)}}}function g(e){return e?.map(_)??[]}function _(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...y(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:Ia(e.checks,_),...y(e.annotations)}}}function v(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function y(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(qy(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function fx(e){return Nd(e)?e.value:{issues:[{message:dre(e.cause)}]}}function yoe(e,t){let n=Tb(e),r={errors:`all`,...t?.parseOptions},i=F_(t),a=e=>{let t=new jo(`sync`),a=am(Dp(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?fx(o):new Promise(e=>{a.addObserver(t=>{e(fx(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}const boe=/*#__PURE__*/ j(2,(e,t)=>Coe(e,(e,n)=>Soe(t,e)?void 0:[e,n])),xoe=/*#__PURE__*/ j(2,(e,t)=>({...e,...t})),px=e=>e;function Soe(e,t){return e.some(e=>e===t||typeof e==`number`&&String(e)===t)}function Coe(e,t){let n={};for(let r of Reflect.ownKeys(e)){if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;let i=t(r,e[r]);if(i){let[e,t]=i;or(n,e,t)}}return n}const mx=`~effect/Schema/SchemaError`;function hx(e){return N(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...er}),{...er},{...er},{...er},{...er},{...er},{...er},{...er};const gx=Mb;function _x(){return(e,t,n)=>Ax(new Mv(e.map(ay),e=>t(e.map(e=>Ax(e))),n))}function vx(e,t){return _x()([],()=>(t,n,r)=>e(t)?F(t):z(new w_(n,t,r)),t)}var yx=class extends (/*#__PURE__*/ Bo(`SchemaError`)){[mx]=mx;constructor(e){let t=nr();rr(0);try{super({issue:e})}finally{rr(t)}}get message(){return H_(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[Qn](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function woe(e){return hx(e)}function bx(e){return vc(e)?Toe(e):hp(e,e=>np(()=>gd(e,e=>new yx(e))))}function Toe(e){return Nd(e)?e:Od(gd(e.cause,e=>new yx(e)))}function Eoe(e,t){let n;for(let r of e.reasons){if(!dd(r)||!woe(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function xx(e){let t=lm(e);if(Nd(t))return t.value;throw Eoe(t.cause,`Sync adapter can only throw schema errors`)}function Doe(e,t){return yoe(e,t)}const Sx=jae;function Cx(e,t){let n=Tb(e,t);return(e,t)=>bx(n(e,t))}const wx=Cx,Ooe=Nae;function koe(e,t){let n=Pae(e,t);return(e,t)=>ste(n(e,t),e=>new yx(e))}function Tx(e,t){let n=Cx(e,t);return(e,t)=>xx(n(e,t))}const Aoe=Tx;function Ex(e,t){let n=Eb(e,t);return(e,t)=>bx(n(e,t))}const Dx=Ex;function Ox(e,t){let n=Ex(e,t);return(e,t)=>xx(n(e,t))}const kx=Ox,Ax=Pb;function jx(e){return N(e,gx)&&e[gx]===gx}const Mx=/*#__PURE__*/ px(e=>Ax(Uy(e.ast),{schema:e})),Nx=/*#__PURE__*/ px(e=>{let t=Qx(e);return Ax(oae(e.ast),{schema:t})}),Px=/*#__PURE__*/ px(e=>Ax(qy(e.ast),{schema:e})),joe=/*#__PURE__*/ px(e=>Ax(Jy(e.ast),{schema:e}));function Fx(e){let t=Ax(new zv(e),{literal:e,transform(n){return t.pipe($x(Fx(n),{decode:nv(()=>n),encode:nv(()=>e)}))}});return t}function Moe(e){return e.map(e=>jx(e)?e.ast:new zv(e))}function Ix(e){return Ax(new Hie(Moe(e)),{parts:e})}const Lx=/*#__PURE__*/ Ax(Bie),Rx=/*#__PURE__*/ Ax(Vie),zx=/*#__PURE__*/ Ax(Iv),Noe=/*#__PURE__*/ Ax(Nv),Poe=/*#__PURE__*/ Ax(Fv),U=/*#__PURE__*/ Ax(Vv),Bx=/*#__PURE__*/ Ax(Uv),Vx=/*#__PURE__*/ Ax(Gie),Hx=/*#__PURE__*/ Ax(zie);function Ux(e,t){return Ax(e,{fields:t,mapFields(e,t){let n=e(this.fields);return Ux(iy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function W(e){return Ux(iy(e,void 0),e)}function Wx(e){return px(t=>t.mapFields(xoe(e)))}function Gx(e,t){return Ax(lae(e.ast,t.ast),{key:e,value:t})}function Kx(e,t){return Ax(Zie(e.ast,t.map(ay)),{schema:e,records:t})}function qx(e,t){return Ax(e,{elements:t,mapElements(e,t){let n=e(this.elements);return qx(oy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function Foe(e){return qx(oy(e),e)}const G=/*#__PURE__*/ px(e=>Ax(new Wv(!1,[],[e.ast]),{value:e})),Jx=/*#__PURE__*/ px(e=>Ax(new Wv(!1,[e.ast],[e.ast]),{value:e}));function Yx(e,t){return Ax(e,{members:t,mapMembers(e,t){let n=e(this.members);return Yx(sy(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function K(e,t){return Yx(sy(e,t,void 0),e)}function Xx(e){let t=e.map(Fx);return Ax(sy(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return K(e(this.members))},pick(e){return Xx(e)},transform(e){return K(t.map((t,n)=>t.transform(e[n])))}})}const Zx=/*#__PURE__*/ px(e=>K([e,Noe])),Qx=/*#__PURE__*/ px(e=>K([e,Poe]));function $x(e,t){return n=>Ax(Wy(n.ast,e.ast,t?dv(t):mv()),{from:n,to:e})}function Ioe(){return(e,t)=>iS()(e,{decode:t,encode:$_})}const Loe=/*#__PURE__*/ Xx([`true`,`yes`,`on`,`1`,`y`]),Roe=/*#__PURE__*/ Xx([`false`,`no`,`off`,`0`,`n`]),zoe=/*#__PURE__*/ Xx([...Loe.literals,...Roe.literals]).pipe(/*#__PURE__*/ $x(Vx,/*#__PURE__*/ pv({decode:e=>e===`true`||e===`yes`||e===`on`||e===`1`||e===`y`,encode:e=>e?`true`:`false`})));function Boe(e){return t=>$x(Px(t),e)(t)}function eS(e){return t=>Ax(sae(t.ast,e),{schema:t})}function tS(e){return Fx(e).pipe(eS(F(e)))}function nS(e,t){return W({_tag:tS(e),...t})}function rS(){return e=>e}function Voe(e,t){return vx(t=>t instanceof e,t)}function iS(){return(e,t)=>new Dv(e.ast,dv(t))}const aS=wy,oS=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Hoe(e){let t=new globalThis.RegExp(oS);return aS(e=>e.trim()===e,{expected:`a string with no leading or trailing whitespace`,representation:{id:`effect/schema/isTrimmed`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isTrimmed()`}),arbitraryConstraint:{patterns:[{source:oS,flags:``}]},...e})}function sS(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${qn(n)})`:`new RegExp(${qn(n)}, ${qn(r)})`;return Ey(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}const cS=/*#__PURE__*/ Ax(Ty);function Uoe(e){let t=ki(e.order),n=e.formatter??qn;return(r,i)=>aS(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function Woe(e){let t=ki(e.order),n=Di(e.order),r=Oi(e.order),i=Ei(e.order),a=e.formatter??qn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return aS(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function lS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${qn(e)}`);return e}const Goe=/*#__PURE__*/ Uoe({order:wi,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:lS(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${qn(e)})`})})}),uS=/*#__PURE__*/ Woe({order:wi,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:lS(e.minimum),maximum:lS(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${qn(e.minimum)}, maximum: ${qn(e.maximum)}, exclusiveMinimum: ${qn(t)}, exclusiveMaximum: ${qn(n)} })`})}}});function Koe(e){return aS(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>({type:`integer`,minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}const dS=/*#__PURE__*/ Bx.check(/*#__PURE__*/ Koe());function fS(e,t){return e=hS(e),pS(e,Math.ceil(e/2),t)}function pS(e,t,n){return aS(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Qg]:!0,arbitraryConstraint:{minLength:e},...n})}function qoe(e){return pS(1,1,e)}function mS(e,t){return e=hS(e),aS(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Qg]:!0,arbitraryConstraint:{maxLength:e},...t})}function hS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Joe(e,t){return e=hS(e),aS(t=>Reflect.ownKeys(t).length>=e,{expected:`a value with at least ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMinProperties`,payload:{minProperties:e}},toJsonSchema:({type:t})=>t===`object`?{minProperties:e}:[{minProperties:e},!0],toCode:()=>({runtime:`Schema.isMinProperties(${e})`}),[Qg]:!0,arbitraryConstraint:{minProperties:e},...t})}function gS(e){return aS(e=>Tte(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitraryConstraint:{uniqueBy:M},...e})}const _S=/*#__PURE__*/ U.check(/*#__PURE__*/ qoe()),Yoe=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),Xoe=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},vS=[];function yS(e){let t=Yoe(e),n=vS[t];if(n!==void 0)return n;let r=JS.pipe($x(zx,Mie(Xoe(t))));return vS[t]=r,r}globalThis.RegExp,globalThis.URL;const Zoe=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function bS(e,t){return Zoe.pipe($x(e,Nie(t)))}const Qoe=/*#__PURE__*/ bS(zx);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;const $oe=/*#__PURE__*/ U.check(/*#__PURE__*/ Hoe()),xS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(/*#__PURE__*/ $x($oe,/*#__PURE__*/ Tie())),SS=/*#__PURE__*/ U.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),CS=/*#__PURE__*/ Voe(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>iS()(SS,_v)}),wS=/*#__PURE__*/ SS.pipe(/*#__PURE__*/ $x(CS,_v));function TS(e,t){let n=_x()([e,t],([e,t])=>(n,r,i)=>{if(!ud(n))return z(new w_(r,n,i));switch(n._tag){case`Fail`:return xm(Tb(e)(n.error,i),{onSuccess:md,onFailure:e=>E_(r,`error`,e,n,i)});case`Die`:return xm(Tb(t)(n.defect,i),{onSuccess:hd,onFailure:e=>E_(r,`defect`,e,n,i)});case`Interrupt`:return F(n)}},{representation:{id:`effect/schema/CauseReason`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.CauseReason(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Failure<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause.Failure`,toCodec:([e,t])=>iS()(K([W({_tag:Fx(`Fail`),error:e}),W({_tag:Fx(`Die`),defect:t}),W({_tag:Fx(`Interrupt`),fiberId:Qx(cS)})]),pv({decode:e=>{switch(e._tag){case`Fail`:return md(e.error);case`Die`:return hd(e.defect);case`Interrupt`:return ore(e.fiberId)}},encode:e=>{switch(e._tag){case`Fail`:return{_tag:`Fail`,error:e.error};case`Die`:return{_tag:`Die`,defect:e.defect};case`Interrupt`:return{_tag:`Interrupt`,fiberId:e.fiberId}}}}))});return Ax(n.ast,{error:e,defect:t})}function ES(e,t){let n=_x()([e,t],([e,t])=>{let n=G(TS(e,t));return(e,t,r)=>ld(e)?xm(Tb(n)(e.reasons,r),{onSuccess:fd,onFailure:n=>E_(t,`failures`,n,e,r)}):z(new w_(t,e,r))},{representation:{id:`effect/schema/Cause`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Cause(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Cause<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause`,toCodec:([e,t])=>iS()(G(TS(e,t)),pv({decode:fd,encode:({reasons:e})=>e}))});return Ax(n.ast,{error:e,defect:t})}const DS=/*#__PURE__*/ fv({decode:(e,t)=>Pi(mh(e),{onNone:()=>z(new T_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>F(hh(e))}),encode:e=>F(_h(e))});function OS(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function kS(e,t){return dS.check(uS({minimum:e,maximum:t}))}const AS=/*#__PURE__*/ vx(e=>uh(e)&&dh(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=OS(e,-864e13,864e13);return Ioe()(kS(t,n),nv(ph))},toCodecJson:()=>iS()(U,DS),toFormatter:()=>e=>e.toString()}),jS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(/*#__PURE__*/ $x(AS,DS));function MS(e,t,n){let r=_x()([e,t,n],([e,t,n])=>{let r=ES(t,n);return(t,n,i)=>{if(!Ed(t))return z(new w_(n,t,i));switch(t._tag){case`Success`:return xm(Tb(e)(t.value,i),{onSuccess:Dd,onFailure:e=>E_(n,`value`,e,t,i)});case`Failure`:return xm(Tb(r)(t.cause,i),{onSuccess:Od,onFailure:e=>E_(n,`cause`,e,t,i)})}}},{representation:{id:`effect/schema/Exit`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Exit(${e[0].runtime}, ${e[1].runtime}, ${e[2].runtime})`,Type:`Exit.Exit<${e[0].Type}, ${e[1].Type}, ${e[2].Type}>`,importDeclarations:[`import * as Exit from "effect/Exit"`]}),expected:`Exit`,toCodec:([e,t,n])=>iS()(K([W({_tag:Fx(`Success`),value:e}),W({_tag:Fx(`Failure`),cause:ES(t,n)})]),pv({decode:e=>e._tag===`Success`?Dd(e.value):Od(e.cause),encode:e=>Nd(e)?{_tag:`Success`,value:e.value}:{_tag:`Failure`,cause:e.cause}}))});return Ax(r.ast,{value:e,error:t,defect:n})}function NS(e,t){let n=typeof t?.label==`string`?t.label:void 0,r=t?.disallowJsonEncode===!0,i=n===void 0?r?{disallowJsonEncode:!0}:void 0:r?{label:n,disallowJsonEncode:!0}:{label:n},a=n===void 0?void 0:Tb(Fx(n)),o=_x()([e],([e])=>(t,n,r)=>{if(ag(t)){let i=a===void 0?L:bm(a(t.label,r),e=>new b_([`label`],e));return Sm(i,()=>xm(Tb(e)(cg(t),r),{onSuccess:e=>og(e,{label:t.label}),onFailure:()=>new C_(n,[new b_([`value`],new T_(void 0,t,r))],t,r)}))}return z(new w_(n,t,r))},{representation:{id:`effect/schema/Redacted`,payload:i??null},toCode:({typeParameters:e})=>({runtime:i===void 0?`Schema.Redacted(${e[0].runtime})`:`Schema.Redacted(${e[0].runtime}, ${qn(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>iS()(e,{decode:nv(e=>og(e,{label:n})),encode:r?Q_(e=>`Cannot serialize Redacted`+(Ni(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):nv(cg)}),toEquivalence:([e])=>lg(e)});return Ax(o.ast,{value:e})}const PS=/*#__PURE__*/ globalThis.Symbol.for(`immer-draftable`),FS={};function IS(e,t,n,r,i){let a=zS(n,t,r),o=RS(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===FS?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:FS,value:i}})}static[gx]=gx;get[o](){return o}static[PS]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return jt(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return Cb(a(this))(e??{},t)}static makeOption(e,t){return Sb(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(Ny(this.ast,e))}static annotateKey(e){return this.rebuild(Hy(this.ast,e))}static check(...e){return this.rebuild(Fy(this.ast,e))}static extend(e){return(t,r)=>{let a=BS(t)?t:W(t),o={...n.fields,...a.fields},s=iy(o,n.ast.checks,{identifier:e});return IS(this,e,Ux(Fy(s,a.ast.checks),o),r,i)}}static mapFields(e,t){return n.mapFields(e,t)}};return i!==void 0&&Object.assign(s.prototype,i(t)),s}function LS(e){return new uv(nv(t=>new e(t,{"~payload":{token:FS,value:t}})),tv())}function RS(e){return`~effect/Schema/Class/${e}`}function zS(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=RS(t),o=e=>e instanceof i||N(e,a),s=LS(i);return r=$x(Ax(new Mv([e.ast],()=>(e,t,n)=>o(e)?F(e):z(new w_(t,e,n)),{identifier:t,[t_]:([e])=>({isConstructed:o,link:new Dv(e,s)}),toCodec:([e])=>new Dv(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[e_]:uy(e.ast),...n})),s)(e)}}function BS(e){return jx(e)}const VS=e=>(t,n)=>{let r=BS(t)?t:W(t);return IS(Fo,e,r,n,e=>({toString(){return`${e}(${qn({...this})})`}}))},HS=e=>(t,n)=>{let r=BS(t)?t:W(t);return IS(Qr,e,r,n,e=>({name:e}))},US=e=>(t,n,r)=>{let i=BS(n)?n.mapFields(e=>({_tag:tS(t),...e}),{unsafePreserveChecks:!0}):nS(t,n);return HS(e??t)(i,r)};function WS(e,t){return hoe(voe(Gb(e.ast),t),t)}const GS=Zae,KS=eoe,qS=toe,JS=/*#__PURE__*/ Ax(/*#__PURE__*/ Ny(ub,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),q=/*#__PURE__*/ Gx(U,JS);function YS(){return Object.assign(e=>e,{option:e=>ji(e),result:e=>ba(e),is:e=>!0})}const XS=Ls,ZS=Rs,QS=Ms,$S=tu,eC=fu,tC=pu,nC=`~effect/MutableRef`,rC={[nC]:nC,...vr,toJSON(){return{_id:`MutableRef`,current:$n(this.current)}}},iC=e=>{let t=Object.create(rC);return t.current=e,t},aC=/*#__PURE__*/ j(2,(e,t)=>(e.current=t,e)),oC=/*#__PURE__*/ Symbol.for(`effect/MutableList/Empty`),sC=()=>({head:void 0,tail:void 0,length:0}),cC=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},lC=()=>({array:[],mutable:!0,offset:0,next:void 0}),uC=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=lC(),e.tail=e.tail.next):e.head=e.tail=lC(),e.tail.array.push(t),e.length++},dC=(e,t)=>{e.head={array:[t],mutable:!0,offset:0,next:e.head},e.tail||=e.head,e.length++},fC=(e,t)=>pC(e,ka(t),!Array.isArray(t)),pC=(e,t,n=!1)=>{if(t.length===0)return 0;let r={array:t,mutable:n,offset:0,next:void 0};return e.head?e.tail=e.tail.next=r:e.head=e.tail=r,e.length+=t.length,t.length},mC=e=>{e.head=e.tail=void 0,e.length=0},hC=(e,t)=>{if(t=ya(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return mC(e),t}let n=Array(t),r=0,i=e.head;for(;i;){for(;i.offset<i.array.length;)if(n[r++]=i.array[i.offset],i.mutable&&(i.array[i.offset]=void 0),i.offset++,r===t)return e.head=i.offset===i.array.length&&i.next?i.next:i,e.length-=t,e.length===0?mC(e):cC(e),n;i=i.next}return mC(e),n},gC=e=>hC(e,e.length),_C=e=>{if(!e.head)return oC;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:mC(e):cC(e),t},vC=(e,t)=>{let n=[],r=e.head,i=0;for(;r;){for(let e=r.offset;e<r.array.length;e++)t(r.array[e],i++)&&n.push(r.array[e]);r=r.next}n.length===0?mC(e):(e.head=e.tail={array:n,mutable:!0,offset:0,next:void 0},e.length=n.length)},yC=(e,t)=>vC(e,e=>e!==t),bC=e=>I(()=>IC(e.atomicPubSub(),/* @__PURE__ */ new Map,qd(),eC(!1),iC(!1),e.strategy(),iC(Ai()))),xC=e=>bC({atomicPubSub:()=>SC(e),strategy:()=>new LC}),SC=e=>{let t=e?.replay;return new MC(t&&t>0?new BC(Math.ceil(t)):void 0)},CC=/*#__PURE__*/ j(2,(e,t)=>Qf(()=>e.shutdownFlag.current||Ni(e.ended.current)?F(!1):e.pubsub.publish(t)?(e.strategy.completeSubscribersUnsafe(e.pubsub,e.subscribers),F(!0)):e.strategy.handleSurplus(e.pubsub,e.subscribers,[t],e.shutdownFlag,e.ended))),wC=e=>Xp(jp(t=>{let n=da(t,Kd),r=Qd(e.scope),i=jC(e.pubsub,e.subscribers,e.strategy,e.ended);return Xd(r,TC(i)).pipe(sp(Yd(n,e=>$d(r,e))),dp(i))})),TC=e=>Xp(ap(t=>(aC(e.shutdownFlag,!0),qf(gC(e.pollers),e=>bre(e,t.id),{discard:!0,concurrency:`unbounded`}).pipe(cp(()=>I(()=>{e.subscribers.delete(e.subscription),e.subscription.unsubscribe(),e.replayWindow.close(),e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers)})),uie(e.shutdownHook.open),fp)))),EC=e=>Qf(()=>{if(e.shutdownFlag.current)return qp;if(e.replayWindow.remaining>0){let t=e.replayWindow.take();return F(t)}let t=e.pollers.length===0?e.subscription.poll():oC;return t===oC?DC(e):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),F(t))}),DC=e=>$f(t=>{if(e.shutdownFlag.current)return t(qp);if(Ni(e.ended.current)){let n=e.pollers.length===0?e.subscription.poll():oC;return n===oC?t(F(e.ended.current.value)):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),t(F(n)))}let n=Ld(),r=e.subscribers.get(e.subscription);return r||(r=/* @__PURE__ */ new Set,e.subscribers.set(e.subscription,r)),r.add(e.pollers),uC(e.pollers,n),e.strategy.completePollersUnsafe(e.pubsub,e.subscribers,e.subscription,e.pollers),n.effect?t(n.effect):(n.resumes=[t],I(()=>yC(e.pollers,n)))}),OC=/*#__PURE__*/ Symbol.for(`effect/PubSub/AbsentValue`),kC=(e,t,n)=>{e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(n)},AC=(e,t,n)=>{if(!e.has(t))return;let r=e.get(t);r.delete(n),r.size===0&&e.delete(t)},jC=(e,t,n,r)=>new PC(e,t,e.subscribe(),sC(),eC(!1),iC(!1),n,e.replayWindow(),r);var MC=class{publisherHead={value:OC,replayIndex:void 0,subscribers:0,next:null};publisherTail=this.publisherHead;publisherIndex=0;subscribersIndex=0;capacity=2**53-1;replayBuffer;constructor(e){this.replayBuffer=e}replayWindow(){return this.replayBuffer?new VC(this.replayBuffer):HC}isEmpty(){return this.publisherHead===this.publisherTail}isFull(){return!1}size(){return this.publisherIndex-this.subscribersIndex}publish(e){let t=this.replayBuffer?.offer(e),n=this.publisherTail.subscribers;if(n!==0){let r={value:e,replayIndex:t,subscribers:n,next:null};this.publisherTail.next=r,this.publisherTail=this.publisherTail.next,this.publisherIndex+=1}return!0}publishAll(e){if(this.publisherTail.subscribers!==0)for(let t of e)this.publish(t);else this.replayBuffer&&this.replayBuffer.offerAll(e);return[]}slide(){if(this.publisherHead!==this.publisherTail){let e=this.publisherHead.next,t=e.value;this.publisherHead=this.publisherHead.next,this.publisherHead.value=OC,this.subscribersIndex+=1,this.replayBuffer?.slide(t,e.replayIndex)}}subscribe(){return this.publisherTail.subscribers+=1,new NC(this,this.publisherTail,this.publisherIndex,!1)}},NC=class{self;subscriberHead;subscriberIndex;unsubscribed;constructor(e,t,n,r){this.self=e,this.subscriberHead=t,this.subscriberIndex=n,this.unsubscribed=r}isEmpty(){if(this.unsubscribed)return!0;let e=!0,t=!0;for(;t;)this.subscriberHead===this.self.publisherTail?t=!1:this.subscriberHead.next.value===OC?(this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1):(e=!1,t=!1);return e}size(){return this.unsubscribed?0:this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(){if(this.unsubscribed)return oC;let e=!0,t=oC;for(;e;)if(this.subscriberHead===this.self.publisherTail)e=!1;else{let n=this.subscriberHead.next.value;n!==OC&&(t=n,--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=OC,this.self.subscribersIndex+=1),e=!1),this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return t}pollUpTo(e){e=ya(e);let t=[],n=0;for(;n!==e;){let r=this.poll();r===oC?n=e:(t.push(r),n+=1)}return t}unsubscribe(){if(!this.unsubscribed)for(this.unsubscribed=!0,--this.self.publisherTail.subscribers;this.subscriberHead!==this.self.publisherTail;)this.subscriberHead.next.value!==OC&&(--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=OC,this.self.subscribersIndex+=1)),this.subscriberHead=this.subscriberHead.next}},PC=class{"~effect/PubSub/Subscription"={_A:M};pubsub;subscribers;subscription;pollers;shutdownHook;shutdownFlag;strategy;replayWindow;ended;constructor(e,t,n,r,i,a,o,s,c){this.pubsub=e,this.subscribers=t,this.subscription=n,this.pollers=r,this.shutdownHook=i,this.shutdownFlag=a,this.strategy=o,this.replayWindow=s,this.ended=c}pipe(){return jt(this,arguments)}},FC=class{"~effect/PubSub"={_A:M};pubsub;subscribers;scope;shutdownHook;shutdownFlag;strategy;ended;constructor(e,t,n,r,i,a,o){this.pubsub=e,this.subscribers=t,this.scope=n,this.shutdownHook=r,this.shutdownFlag=i,this.strategy=a,this.ended=o}pipe(){return jt(this,arguments)}};const IC=(e,t,n,r,i,a,o)=>new FC(e,t,n,r,i,a,o);var LC=class{get shutdown(){return L}handleSurplus(e,t,n,r){return F(!1)}onPubSubEmptySpaceUnsafe(e,t){}completePollersUnsafe(e,t,n,r){return RC(this,e,t,n,r)}completeSubscribersUnsafe(e,t){return zC(this,e,t)}};const RC=(e,t,n,r,i)=>{let a=!0;for(;a&&!r.isEmpty();){let o=_C(i);if(o===oC)AC(n,r,i),i.length===0?a=!1:kC(n,r,i);else{let a=r.poll();a===oC?dC(i,o):(Wd(o,Dd(a)),e.onPubSubEmptySpaceUnsafe(t,n))}}},zC=(e,t,n)=>{for(let[r,i]of n)for(let a of i)e.completePollersUnsafe(t,n,r,a)};var BC=class{capacity;head={value:OC,index:0,next:null};tail=this.head;slideValues=[];size=0;index=0;publisherIndex=0;constructor(e){this.capacity=e}slide(e,t){this.slideValues[this.index%this.capacity]={value:e,index:t},this.index++}offer(e){let t=this.publisherIndex++;return this.tail.value=e,this.tail.index=t,this.tail.next={value:OC,index:0,next:null},this.tail=this.tail.next,this.size===this.capacity?this.head=this.head.next:this.size+=1,t}offerAll(e){for(let t of e)this.offer(t)}},VC=class{buffer;values;index=0;remaining;slideIndex;newestIndex=-1;constructor(e){this.buffer=e,this.remaining=e.size,this.slideIndex=e.index,this.values=Array(this.remaining);let t=e.head;for(let e=0;e<this.remaining;e++)this.values[e]=t.value,this.newestIndex=t.index,t=t.next}close(){this.values.length=0,this.remaining=0}sync(){let e=this.buffer.index-this.slideIndex;if(e===0||this.remaining===0)return;let t=Math.min(e,this.buffer.capacity),n=this.buffer.index-t;for(let e=0;e<t;e++){let t=this.buffer.slideValues[(n+e)%this.buffer.capacity];t.index>this.newestIndex&&(this.index=(this.index+1)%this.values.length,this.values[(this.index+this.remaining-1)%this.values.length]=t.value,this.newestIndex=t.index)}this.slideIndex=this.buffer.index}take(){if(this.remaining===0)return;this.sync();let e=this.values[this.index];return this.values[this.index]=OC,this.index=(this.index+1)%this.values.length,this.remaining--,this.remaining===0&&this.close(),e}takeN(e){e=ya(e);let t=Math.min(e,this.remaining),n=Array(t);for(let e=0;e<t;e++)n[e]=this.take();return n}takeAll(){return this.takeN(this.remaining)}};const HC={remaining:0,take:()=>void 0,takeN:()=>[],takeAll:()=>[],close:()=>void 0},UC={_A:M,_E:M},WC={"~effect/Queue":UC,"~effect/Queue/Enqueue":UC,"~effect/Queue/Dequeue":UC,...vr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:uw(this)}}},GC=e=>Zr(t=>{let n=Object.create(WC);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=sC(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Set,awaiters:/* @__PURE__ */ new Set},Bs(n)}),KC=e=>GC({capacity:e}),qC=e=>GC({capacity:e,strategy:`dropping`}),JC=/*#__PURE__*/ j(2,(e,t)=>Ws(()=>YC(e,t)?fw:e.state._tag===`Open`&&e.strategy===`suspend`?xw(e,t):dw)),YC=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(_C(e.messages),uC(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(uC(e.messages,t),hw(e),!0):(uC(e.messages,t),gw(e),!0):!1,XC=/*#__PURE__*/ j(2,(e,t)=>Zs(n=>{let r=ZC(e,t);return r.length===0||e.strategy===`dropping`?n(Gr(r)):Sw(e,{_tag:`Array`,remaining:r,offset:0,resume:n})})),ZC=(e,t)=>{if(e.state._tag!==`Open`)return ka(t);if(e.capacity===1/0||e.strategy===`sliding`)return fC(e.messages,t),e.strategy===`sliding`&&hC(e.messages,e.messages.length-e.capacity),gw(e),[];let n=e.capacity<=0?e.state.takers.size:e.capacity-e.messages.length;if(n===0)return ka(t);let r=[],i=0;for(let a of t)i<n?uC(e.messages,a):r.push(a),i++;return gw(e),r},QC=/*#__PURE__*/ j(2,(e,t)=>Us(()=>$C(e,t))),$C=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Jr(t),r=kne(n,pw);return e.state.offers.size===0&&e.messages.length===0?(Ew(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},gw(e),!0)},ew=e=>QC(e,Fr(ri())),tw=e=>$C(e,Fr(ri())),nw=e=>Us(()=>rw(e)),rw=e=>{if(e.state._tag===`Done`)return!1;mC(e.messages);let t=e.state.offers;Ew(e,e.state._tag===`Open`?mw:e.state.exit);for(let e of t)Cw(e);return!0},iw=e=>ow(e,1,1/0),aw=e=>Ws(()=>{let t=Pa();return ac(If(Vl({while:Ft,body:Pt(iw(e)),step(e){for(let n=0;n<e.length;n++)t.push(e[n])}}),()=>Ys),t)}),ow=/*#__PURE__*/ j(3,(e,t,n)=>(t=ya(t),n=ya(n),vw(()=>_w(e,t,n)??pc(bw(e,()=>yw(e,t)),ow(e,t,n))))),sw=e=>vw(()=>lw(e)??pc(bw(e,()=>yw(e,1)),sw(e))),cw=e=>vw(()=>{let t=lw(e);return t===void 0?Bs(Ai()):t._tag===`Success`?Bs(ji(t.value)):Bs(Ai())}),lw=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=_C(e.messages);return Tw(e),Gr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=ww(e.state.offers);return Tw(e),Gr(t)}},uw=e=>e.state._tag===`Done`?0:e.messages.length,dw=/*#__PURE__*/ Gr(!1),fw=/*#__PURE__*/ Gr(!0),pw=/*#__PURE__*/ Yr(/*#__PURE__*/ ri()),mw=/*#__PURE__*/ bc(),hw=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(Cc),e.messages.length===0))break}},gw=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,hw(e)},0))},_w=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Gr([]);if(!yw(e,t))return;let r=e.messages.length>0?hC(e.messages,n):[ww(e.state.offers)];return Tw(e),Gr(r)},vw=/*#__PURE__*/ Ur({op:`QueueTake`,[pr](e){let t=this[fr]();return xr(t)?t[pr](e):t}}),yw=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,bw=(e,t)=>Zs(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(Cc);let r={ready:t,resume:n};return e.state.takers.add(r),Us(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),xw=(e,t)=>Zs(n=>YC(e,t)?n(fw):Sw(e,{_tag:`Single`,message:t,resume:n})),Sw=(e,t)=>{if(e.state._tag!==`Open`)return Cw(t);let n=e.state.offers;return n.add(t),Us(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&Ew(e,e.state.exit))})},Cw=e=>e._tag===`Single`?e.resume(dw):e.resume(Gr(e.remaining.slice(e.offset))),ww=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(fw),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Gr([]))),n},Tw=e=>{if(e.state._tag===`Done`)return Lf(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(Ew(e,e.state.exit),Lf(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)uC(e.messages,t.message),e.state.offers.delete(t),t.resume(fw);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;uC(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Gr([]))}let r=e.state;if(r._tag===`Done`)return Lf(r.exit.cause)}return!1},Ew=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},Dw=e=>new kw(e),Ow=(e,t,n)=>Zs(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),Us(()=>{e.waiters.delete(i)})});var kw=class{waiters=/*#__PURE__*/ new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Ws(()=>this.free<e?Ow(this,e,t):(this.taken+=e,Bs(e)));return t}takeIfAvailable(e){return Ws(()=>this.free<e?Bs(!1):(this.taken+=e,Bs(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return Zr(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Ys))}release(e){return Zr(t=>Bs(this.releaseUnsafe(t,e)))}get releaseAll(){return Zr(e=>Bs(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>zl(n=>{let r=Ws(()=>{if(this.free<e){let t=Ow(this,e,Ys);return _c(n(t),()=>r)}return this.taken+=e,yl(n(t),()=>{this.releaseUnsafe(Ms(),e)},!0)});return r})}withPermit=/*#__PURE__*/ this.withPermits(1);withPermitsIfAvailable(e){return t=>zl(n=>this.free<e?Ks:(this.taken+=e,yl(n(fc(t)),()=>{this.releaseUnsafe(Ms(),e)},!0)))}};const Aw=e=>Us(()=>new kw(e)),jw=`~effect/Channel`,Mw=e=>N(e,jw),Nw={[jw]:{_Env:M,_InErr:M,_InElem:M,_OutErr:M,_OutElem:M},pipe(){return jt(this,arguments)}},Pw=e=>{let t=Object.create(Nw);return t.transform=(t,n)=>hp(e(t,n),e=>F(tp(e))),t},Fw=(e,t)=>Pw((n,r)=>B(Rw(e)(n,r),e=>t(e,r))),Iw=e=>Pw((t,n)=>e),Lw=e=>Pw(H(function*(t,n){let r=Qd(n),i=e=>$d(r,Bf(e)),a=yield*Up(e(t,n,r),i);return Up(a,i)})),Rw=e=>e.transform,zw=(e,t,n)=>GC({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(cp(t=>Xd(e,nw(t))),cp(n=>Jd(t(n),e).pipe(hp(e=>QC(n,e)),rm(e)))),Bw=(e,t)=>Pw((n,r)=>V(zw(r,e,t),iw)),Vw=e=>Pw((t,n)=>Qf(()=>Rw(e())(t,n))),Hw=e=>Iw(I(()=>{let t=e();return Qf(()=>{let e=t.next();return e.done?Sd(e.value):F(e.value)})})),Uw=e=>Jw(F(e)),Ww=/*#__PURE__*/ Iw(/*#__PURE__*/ F(/*#__PURE__*/ Sd())),Gw=e=>Iw(F(z(e))),Kw=e=>Iw(tp(e)),qw=e=>Kw(pd(e)),Jw=e=>Iw(I(()=>{let t=!1;return Qf(()=>t?Sd():(t=!0,e))})),Yw=e=>Iw(B(e,()=>Sd())),Xw=e=>Iw(F(iw(e))),Zw=e=>Pw((t,n)=>Qw({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),Qw=e=>{let t=e.readable.getReader(),n=e.exit??iC(void 0),r=Qf(()=>n.current?n.current:Op(Xf({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??tp(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Sd():F(Fa(t))}));return dp(Xd(e.scope,e.releaseLockOnEnd?I(()=>t.releaseLock()):Yf(()=>t.cancel().catch(Rt))),r)},$w=/*#__PURE__*/ j(2,(e,t)=>Fw(e,e=>I(()=>{let n=0;return V(e,e=>t(e,n++))}))),eT=/*#__PURE__*/ j(2,(e,t)=>tT(e,e=>F(t(e)))),tT=/*#__PURE__*/ j(2,(e,t)=>Fw(e,e=>F(If(e,e=>B(t(e),Sd))))),nT=e=>e===void 0||e!==`unbounded`&&e<=1,rT=/*#__PURE__*/ j(e=>Mw(e[0]),(e,t,n)=>nT(n?.concurrency)?iT(e,t):aT(e,t,n)),iT=(e,t)=>Pw((n,r)=>{let i=0;return V(Rw(e)(n,r),B(e=>t(e,i++)))}),aT=(e,t,n)=>Lw(H(function*(r,i,a){let o=0,s=yield*Rw(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*KC(0);yield*Xd(a,nw(l));let u=om(yield*Ap()),d=$S(a);if(n.unordered){let e=Dw(c),n=Pt(e.release(1)),r=Op({onFailure:e=>B(QC(l,e),n),onSuccess:e=>B(JC(l,e),n)});yield*e.take(1).pipe(B(()=>s),B(e=>{let n=o++;return d(u(r(Qf(()=>t(e,n))))),L}),Qp({disableYield:!0}),hp(t=>e.withPermits(c-1)(QC(l,t))),rm(a))}else{let e=yield*KC(c-2);yield*Xd(a,nw(e)),yield*sw(e).pipe(tie,B(e=>JC(l,e)),Qp({disableYield:!0}),hp(e=>QC(l,e)),rm(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,$C(l,e.cause))};yield*s.pipe(B(i=>{if(n)return tp(n);let a=o++,s=u(Qf(()=>t(i,a)));return d(s),s.addObserver(r),JC(e,XS(s))}),Qp({disableYield:!0}),hp(t=>JC(e,Od(t)).pipe(sp(QC(e,t)))),rm(a))}return sw(l)})),oT=/*#__PURE__*/ j(e=>Mw(e[0]),(e,t,n)=>nT(n?.concurrency)?sT(e,t):cT(e,t,n)),sT=(e,t)=>Pw((n,r)=>V(Rw(e)(n,r),e=>{let i,a,o=B(e,e=>(a??=Qd(r),Sm(Rw(t(e))(n,a),e=>(i=s(e),i)))),s=If(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=$d(a,Md);return a=void 0,B(t,()=>o)});return Qf(()=>i??o)})),cT=(e,t,n)=>e.pipe($w(t),hT(n)),lT=e=>oT(e,M),uT=/*#__PURE__*/ j(2,(e,t)=>Pw((n,r)=>{let i=Qd(r);return V(Rw(e)(n,i),e=>{let a=e.pipe(hp(e=>{if(Lf(e))return tp(e);let o=i;return i=Qd(r),$d(o,Od(e)).pipe(sp(Rw(t(e))(n,i)),B(e=>(a=e,e)))}));return Qf(()=>a)})})),dT=/*#__PURE__*/ j(2,(e,t)=>uT(e,e=>Yw(B(t(e),t=>tp(e))))),fT=/*#__PURE__*/ j(3,(e,t,n)=>uT(e,e=>{let r=t(e);return Ca(r)?Kw(r.failure):n(r.success,e)})),pT=/*#__PURE__*/ j(2,(e,t)=>fT(e,lre,e=>t(e))),mT=e=>pT(e,qw),hT=/*#__PURE__*/ j(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>Lw(H(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:Dw(s),l=yield*tC(!0),u=/* @__PURE__ */ new Set,d=yield*KC(t);yield*Xd(o,nw(d));let f=yield*Rw(e)(i,a);return yield*R(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*nm(f),yield*Ep(c.take(1),sp(XS(e),ep))));let t=e===void 0?yield*f:yield*XS(e),n=Qd(o),r=yield*Rw(t)(i,n);for(;u.size>=s;){let e=dte(u);u.delete(e),u.size===0&&(yield*l.open),yield*ZS(e)}let a=yield*r.pipe(cp(()=>eie),B(e=>JC(d,e)),Qp({disableYield:!0}),Up(H(function*(e){let t=Bf(e),r=yield*up($d(n,t));if(!u.has(a))return;let i=gre([t,r]);Pd(i)&&(yield*QC(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),nm);l.closeUnsafe(),u.add(a)}}).pipe(hp(e=>{let t=zf(e);return wa(t)?l.whenOpen(QC(d,e)):QC(d,e)}),rm(o)),sw(d)}))),gT=/*#__PURE__*/ j(e=>Mw(e[0])&&Mw(e[1]),(e,t,n)=>Lw(H(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*KC(0);yield*Xd(a,nw(s));let c=0;function l(e,t){if(c++,!Lf(t))return QC(s,t);switch(o){case`both`:return c===2?QC(s,t):L;case`left`:case`right`:return e===o?QC(s,t):L;case`either`:return QC(s,t)}}let u=(e,t,n)=>Rw(t)(r,n).pipe(B(e=>e.pipe(B(e=>JC(s,e)),Qp)),Up(t=>Wp(Bf(t),e=>$d(n,e)).pipe(Op({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),rm(a));return yield*u(`left`,e,Qd(a)),yield*u(`right`,t,Qd(a)),sw(s)}))),_T=()=>Pw((e,t)=>I(()=>{let t=``,n=!1,r=Ai();function i(e){let r=[];function i(e){t.length===0?r.push(e):(r.push(t+e),t=``)}for(let r=0;r<e.length;r++){let a=e[r];if(a.length!==0){let e=0,r=a.indexOf(`\r`),o=a.indexOf(`
|
|
17
|
+
`);for(n&&=(o===0&&(e=1,o=a.indexOf(`
|
|
18
|
+
`,e)),!1);r!==-1||o!==-1;)r===-1||o!==-1&&o<r?(i(a.substring(e,o)),e=o+1,o=a.indexOf(`
|
|
19
|
+
`,e)):(i(a.substring(e,r)),a.length===r+1?(n=!0,e=a.length,r=-1):(e=r+(o===r+1?2:1),r=a.indexOf(`\r`,e),o=a.indexOf(`
|
|
20
|
+
`,e)));t+=a.substring(e)}}return Na(r)?r:null}let a=Qf(()=>r._tag===`Some`?Sd(r.value):Wre(e,{onSuccess:o,onFailure:tp,onDone:e=>{if(r=ji(e),t.length>0){let e=t;return t=``,n=!1,F([e])}return Sd(e)}}));function o(e){let t=i(e);return t===null?a:F(t)}return a})),vT=/*#__PURE__*/ j(2,(e,t)=>Pw((n,r)=>B(Rw(e)(n,r),e=>Rw(t)(e,r)))),yT=/*#__PURE__*/ j(2,(e,t)=>Pw((n,r)=>B(Rw(e)(n,r),e=>{let n=hp(e,e=>Lf(e)?tp(e):rp(xd(e)));return V(Rw(t)(n,r),e=>gp(e,e=>bd(e)?tp(e.value):rp(e)))}))),bT=e=>Pw((t,n)=>{let r;return F(Qf(()=>r||e.pipe(Jd(n),B(e=>Rw(e)(t,n)),B(e=>r=e))))}),xT=/*#__PURE__*/ j(2,(e,t)=>Lw((n,r,i)=>Yd(i,t).pipe(sp(Rw(e)(n,r))))),ST=/*#__PURE__*/ j(2,(e,t)=>xT(e,e=>t)),CT=(e,t,n)=>Qf(()=>{let r=qd(),i=Rw(e)(Sd(),r);return If(B(i,t),n||F).pipe(Gp(e=>$d(r,e)))}),wT=/*#__PURE__*/ j(2,(e,t)=>Pw((n,r)=>V(Np(Rw(e)(n,r),t),Np(t)))),TT=/*#__PURE__*/ j(2,(e,t)=>CT(e,e=>Qp(B(e,t),{disableYield:!0}))),ET=/*#__PURE__*/ j(3,(e,t,n)=>Qf(()=>{let r=t();return CT(e,e=>Jf({while:Ft,body:()=>e,step:e=>{r=n(r,e)}}),()=>F(r))})),DT=(e,t)=>Rw(e)(Sd(),t),OT=`~effect/PlatformError`;var kT=class extends (/*#__PURE__*/ Bo(`BadArgument`)){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:``}`}},AT=class extends zo{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor===void 0?``:` (${this.pathOrDescriptor})`}${this.description?`: ${this.description}`:``}`}},jT=class extends (/*#__PURE__*/ Bo(`PlatformError`)){constructor(e){`cause`in e?super({reason:e,cause:e.cause}):super({reason:e})}[OT]=OT;get message(){return this.reason.message}};const MT=e=>new jT(new AT(e)),NT=e=>new jT(new kT(e)),PT={_R:M,_E:M,_A:M},FT=function(e){this.channel=e};FT.prototype={"~effect/Stream":PT,pipe(){return jt(this,arguments)}};const IT=e=>new FT(e),LT=`~effect/Sink`,RT=/*#__PURE__*/ F([void 0]),zT={_A:M,_In:M,_L:M,_E:M,_R:M},BT={[LT]:zT,pipe(){return jt(this,arguments)}},VT=e=>N(e,LT),HT=e=>UT((t,n)=>Rw(e)(t,n).pipe(B(Qp({disableYield:!0})),If(F))),UT=e=>{let t=Object.create(BT);return t.transform=e,t},WT=e=>Pw((t,n)=>F(B(e.transform(t,n),Sd))),GT=/*#__PURE__*/ UT(e=>If(Qp(e,{disableYield:!0}),()=>RT)),KT=e=>qT(qf(t=>e(t),{discard:!0})),qT=e=>UT(t=>t.pipe(B(e),Qp({disableYield:!0}),If(()=>RT))),JT=e=>HT(bT(V(e,WT))),YT=`~effect/RcMap`,XT=e=>({[YT]:YT,lookup:e.lookup,context:e.context,scope:e.scope,idleTimeToLive:e.idleTimeToLive,capacity:e.capacity,state:{_tag:`Open`,map:Jre()},pipe(){return jt(this,arguments)}}),ZT=e=>ap(t=>{let n=t.context,r=da(n,Kd),i=XT({lookup:e.lookup,context:n,scope:r,idleTimeToLive:typeof e.idleTimeToLive==`function`?Bt(e.idleTimeToLive,Ja):Pt(Ja(e.idleTimeToLive??oo)),capacity:Math.max(e.capacity??1/0,0)});return dp(Yd(r,()=>{if(i.state._tag===`Closed`)return L;let e=i.state.map;return i.state={_tag:`Closed`},qf(e,([,e])=>up(eE(e))).pipe(cp(()=>I(()=>{Qre(e)})))}),i)}),QT=/*#__PURE__*/ j(2,(e,t)=>Zp(n=>{if(e.state._tag===`Closed`)return qp;let r=e.state,i=QS(),a=Hf(r.map,t),o;if(a._tag===`Some`)o=a.value,o.refCount++;else if(Number.isFinite(e.capacity)&&$re(e.state.map)>=e.capacity)return z(new pre(`RcMap attempted to exceed capacity of ${e.capacity}`));else{o={deferred:Ld(),scope:qd(),idleTimeToLive:e.idleTimeToLive(t),finalizer:void 0,fiber:void 0,expiresAt:0,refCount:1},o.finalizer=tE(e,t,o),Xre(r.map,t,o);let n=new Map(e.context.mapUnsafe);i.context.mapUnsafe.forEach((e,t)=>{n.set(t,e)}),n.set(Kd.key,o.scope);let a=ta(n);Qf(()=>e.lookup(t)).pipe(om(a),$S(o.scope)).addObserver(n=>{hre(n)&&$T(e,t,o,a),Wd(o.deferred,n)})}let s=ua(i.context,Kd);return Xd(s,o.finalizer).pipe(sp(n(zd(o.deferred))))})),$T=(e,t,n,r)=>{if(e.state._tag===`Closed`)return;let i=Hf(e.state.map,t);i._tag!==`None`&&i.value===n&&(Wf(e.state.map,t),!(n.refCount>0)&&eE(n).pipe(om(r),$S(e.scope)))},eE=e=>e.fiber?ZS(e.fiber).pipe(sp($d(e.scope,Md))):$d(e.scope,Md),tE=(e,t,n)=>ap(r=>{if(n.refCount--,n.refCount>0)return L;if(e.state._tag===`Closed`)return eE(n);let i=Hf(e.state.map,t);if(i._tag===`None`||i.value!==n)return eE(n);if(ro(n.idleTimeToLive))return Wf(e.state.map,t),eE(n);if(!no(n.idleTimeToLive))return L;let a=r.getRef(Tf);return n.expiresAt=a.currentTimeMillisUnsafe()+_o(n.idleTimeToLive),n.fiber||=Zp(function r(i){let o=a.currentTimeMillisUnsafe(),s=n.expiresAt-o;if(s<=0){if(e.state._tag===`Closed`||n.refCount>0)return L;let r=Hf(e.state.map,t);return r._tag===`None`||r.value!==n?L:(Wf(e.state.map,t),$d(n.scope,Md))}return B(i(a.sleep(uo(s))),()=>r(i))}).pipe(Hp(I(()=>{n.fiber=void 0})),om(r.context),$S(e.scope)),L}),nE={_tag:`Empty`},rE={_tag:`Closed`},iE={_A:M,_E:M};var aE=class{"~effect/RcRef"=iE;pipe(){return jt(this,arguments)}state=nE;acquire;context;scope;idleTimeToLive;constructor(e,t,n,r){this.acquire=e,this.context=t,this.scope=n,this.idleTimeToLive=r}};const oE=e=>ap(t=>{let n=t.context,r=da(n,Kd),i=new aE(e.acquire,n,r,e.idleTimeToLive===void 0?void 0:Ja(e.idleTimeToLive));return dp(Yd(r,()=>{let e=i.state;return i.state=rE,e._tag===`Acquired`?$d(e.scope,Md):e._tag===`Acquiring`?ZS(e.fiber):L}),i)}),sE=(e,t)=>{switch(e.state._tag){case`Closed`:return qp;case`Acquired`:{let t=e.state;return t.refCount++,t.fiber?dp(ZS(t.fiber),t):F(t)}case`Acquiring`:{let n=e.state;return n.awaiters++,cE(e,n,t)}case`Empty`:{let n={_tag:`Acquiring`,fiber:void 0,awaiters:1,acquired:void 0};e.state=n;let r=qd(),i=Np(e.acquire,oa(e.context,Kd,r)).pipe(B(t=>{if(e.state!==n)return qp;let i={_tag:`Acquired`,value:t,scope:r,fiber:void 0,refCount:n.awaiters,invalidated:!1};return e.state=i,n.acquired=i,F(i)}),Gp(t=>Nd(t)?L:(e.state===n&&(e.state=nE),$d(r,t))));return n.fiber=om(QS().context)(i),cE(e,n,t)}}},cE=(e,t,n)=>Gp(n(XS(t.fiber)),n=>{let r=t.acquired;return r===void 0?--t.awaiters>0||e.state!==t?L:(e.state=nE,ZS(t.fiber)):Pd(n)?uE(e,r):L}),lE=e=>{let t=e;return Zp(e=>B(Rp,n=>B(sE(t,e),e=>dp(Yd(n,()=>uE(t,e)),e.value))))},uE=(e,t)=>{if(t.refCount--,t.refCount>0)return L;let n=e.idleTimeToLive;return n===void 0||t.invalidated?(e.state===t&&(e.state=nE),$d(t.scope,Md)):(no(n)&&(t.fiber=Zp(r=>B(r(Tp(n)),()=>e.state===t&&t.refCount===0?(e.state=nE,$d(t.scope,Md)):L)).pipe(Hp(I(()=>{t.fiber=void 0})),om(e.context),$S(e.scope))),L)},dE=oE,fE=lE,pE=e=>N(e,`~effect/Stream`),mE=IT,hE=e=>mE(Jw(V(e,Fa))),gE=e=>_E(I(()=>{let t=!0,n=F(Fa(void 0)),r=sie(n,e);return Qf(()=>t?(t=!1,n):r)})),_E=e=>mE(Iw(e)),vE=(e,t)=>mE(Pw((n,r)=>B(DT(e.channel,r),e=>t(e,r)))),yE=e=>e.channel,bE=(e,t)=>mE(Bw(e,t)),xE=/*#__PURE__*/ mE(Ww),SE=e=>mE(Vw(()=>e().channel)),CE=e=>mE(Gw(e)),wE=e=>Na(e)?mE(Uw(e)):xE,TE=e=>mE(Xw(e)),EE=e=>mE(Zw(e)),DE=e=>mE(bT(V(e,yE))),OE=/*#__PURE__*/ j(2,(e,t)=>SE(()=>{let n=0;return mE($w(e.channel,Ia(e=>t(e,n++))))})),kE=/*#__PURE__*/ j(2,(e,t)=>mE(rT(e.channel,t))),AE=/*#__PURE__*/ j(2,(e,t)=>{let n=mE(lT(Hw(()=>ME(e,t))));return jE.set(n,[e,t]),n}),jE=/*#__PURE__*/ new WeakMap;function*ME(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=jE.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}const NE=/*#__PURE__*/ j(e=>pE(e[0])&&pE(e[1]),(e,t,n)=>mE(gT(yE(e),yE(t),n))),PE=/*#__PURE__*/ j(2,(e,t)=>e.channel.pipe(uT(e=>t(e).channel),mE)),FE=/*#__PURE__*/ j(2,(e,t)=>e.channel.pipe(dT(t),mE)),IE=e=>mE(mT(e.channel)),LE=/*#__PURE__*/ j(2,(e,t)=>{let n=ya(t);return n===0?e:vE(e,(e,t)=>I(()=>{let t=0,r=e.pipe(B(e=>t>=n?F(e):(t+=e.length,t<=n?r:F(e.slice(n-t)))));return r}))}),RE=/*#__PURE__*/ j(2,(e,t)=>vE(e,(e,n)=>I(()=>{let r,i,a=Qf(()=>{if(i!==void 0){let e=i;return i=void 0,F(e)}return e}).pipe(pp(e=>(r=kd(e),Sd()))),o=V(Qf(()=>t.transform(a,n)),([e,t])=>(i=t,Fa(e)));return Qf(()=>r||o)}))),zE=/*#__PURE__*/ j(2,(e,t)=>mE(yT(e.channel,t))),BE=/*#__PURE__*/ j(e=>pE(e[0]),(e,t)=>SE(()=>{let n=new TextDecoder(t?.encoding);return OE(e,e=>n.decode(e,{stream:!0}))})),VE=e=>SE(()=>{let t=new TextEncoder;return OE(e,e=>t.encode(e))}),HE=e=>e.channel.pipe(vT(_T()),mE),UE=/*#__PURE__*/ j(2,(e,t)=>mE(ST(e.channel,t))),WE=/*#__PURE__*/ j(2,(e,t)=>mE(wT(e.channel,t))),GE=/*#__PURE__*/ j(2,(e,t)=>pie(n=>DT(e.channel,n).pipe(B(e=>t.transform(e,n)),V(([e])=>e)))),KE=e=>ET(e.channel,()=>[],(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n]);return e}),qE=/*#__PURE__*/ j(2,(e,t)=>TT(e.channel,e=>{let n=0;return Jf({while:()=>n<e.length,body:()=>t(e[n++]),step:Rt})})),JE=/*#__PURE__*/ j(2,(e,t)=>TT(e.channel,t)),YE=e=>ET(e.channel,()=>``,(e,t)=>e+t.join(``)),XE=/*#__PURE__*/ j(e=>pE(e[0]),(e,t,n)=>{let r,i,a=!1,o=eC(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=am(Np(JE(e,e=>o.whenOpen(I(()=>{o.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0}))),t)),i.addObserver(e=>{s?.removeEventListener(`abort`,c),!a&&(e._tag===`Failure`&&s?.aborted!==!0?n.error(_d(e.cause)):n.close())}),s!==void 0&&i.pollUnsafe()===void 0&&(s.aborted?c():s.addEventListener(`abort`,c,{once:!0}))},pull(){return new Promise(e=>{r=e,o.openUnsafe()})},cancel(){if(i)return a=!0,sm(fp(ZS(i)))}},n?.strategy)}),ZE=/*#__PURE__*/ j(e=>pE(e[0]),(e,t)=>V(Ap(),n=>XE(e,n,t))),QE=`~effect/FileSystem`,$E=/*#__PURE__*/ P(`effect/FileSystem`),eD=e=>$E.of({...e,[QE]:QE,exists:t=>zt(e.access(t),dp(!0),mp(`PlatformError`,e=>e.reason._tag===`NotFound`?F(!1):z(e))),readFileString:(t,n)=>B(e.readFile(t),e=>ip({try:()=>new TextDecoder(n).decode(e),catch:e=>NT({module:`FileSystem`,method:`readFileString`,description:`invalid encoding`,cause:e})})),stream:H(function*(t,n){let r=yield*e.open(t,{flag:`r`}),i=n?.offset===void 0?void 0:oh(n.offset);i&&(yield*r.seek(i,`start`));let a=n?.bytesToRead===void 0?void 0:oh(n.bytesToRead),o=BigInt(0),s=Number(BigInt(n?.chunkSize??65536)),c=r.readAlloc(s);return _E(F(B(Qf(()=>a!==void 0&&a<=o?Sd():a!==void 0&&a-o<s?r.readAlloc(Number(a-o)):c),Pi({onNone:()=>Sd(),onSome:e=>(o+=BigInt(e.length),F(Fa(e)))}))))},DE),sink:(t,n)=>zt(e.open(t,{...n,flag:n?.flag??`w`}),V(e=>KT(t=>e.writeAll(t))),JT),writeFileString:(t,n,r)=>B(ip({try:()=>new TextEncoder().encode(n),catch:e=>NT({module:`FileSystem`,method:`writeFileString`,description:`could not encode string`,cause:e})}),n=>e.writeFile(t,n,r))}),tD=`~effect/FileSystem/File`;var nD=class extends (/*#__PURE__*/ P()(`effect/FileSystem/WatchBackend`)){};const rD=`~effect/Path`,iD=/*#__PURE__*/ P(`effect/Path`),aD=e=>iD.of({...e,[rD]:rD,resolveWithin(t,n){if(e.parse(n).root!==``)return Ai();let r=e.resolve(t),i=e.resolve(r,n),a=e.relative(r,i);return a===`..`||a.startsWith(`..${e.sep}`)||e.isAbsolute(a)?Ai():ji(i)}});function oD(e){return{_tag:`Value`,value:e}}function sD(e,t){return{_tag:`Record`,keys:e,value:t}}function cD(e,t){return{_tag:`Array`,length:e,value:t}}const lD=/*#__PURE__*/ _a(`effect/ConfigProvider`,{defaultValue:()=>_D()}),uD={...vr,toJSON(){return{_id:`ConfigProvider`}}},dD=e=>e;function fD(e,t){let n=Object.create(uD);return n.load=e,n.mapInput=t,n}function pD(e,t){return fD(n=>e(t(n)),n=>pD(e,e=>n(t(e))))}function mD(e){return pD(e,dD)}function hD(e,t){return e===``&&!t?void 0:e}function gD(e,t){let n=t?.preserveEmptyStrings===!0,r=vD(e);return mD(t=>F(yD(r,e,t,n)))}function _D(e){return gD(e?.env??{...globalThis.process?.env,...import.meta.env},{preserveEmptyStrings:e?.preserveEmptyStrings})}function vD(e){let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=n.split(`_`),i=t;for(let t of e){let e=i.children??=Object.create(null);i=e[t]??={}}}return t}function yD(e,t,n,r){let i=n.map(String).join(`_`),a=hD(Object.hasOwn(t,i)?t[i]:void 0,r),o=bD(e,n),s=o?.children?Object.keys(o.children):[];return s.length===0?a===void 0?void 0:oD(a):s.every(yte)?cD(Math.max(...s.map(e=>parseInt(e,10)))+1,a):sD(new Set(s),a)}function bD(e,t){if(t.length===0)return e;let n=e;for(let e of t)if(n=n?.children?.[String(e)],!n)return;return n}const xD=/*#__PURE__*/ ki(qu),SD=`~effect/Config`;var CD=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}};const wD={.../*#__PURE__*/ ii({label:`Config`,evaluate(e){return this.parse(e.getRef(lD))}}),[SD]:SD,toJSON(){return{_id:`Config`}}};function TD(e){let t=Object.create(wD);return t.evaluator=e,t.parse=t=>Sm(e(t,[]),op),t}const ED=(e,t,n)=>e.evaluator(t,n),DD=/*#__PURE__*/ j(2,(e,t)=>TD((n,r)=>ym(ED(e,n,r),e=>Ca(e)?ba(t):e))),OD=e=>ln(e,`SourceError`),kD=()=>`<configuration>`,AD=e=>t=>hp(t,t=>tp(fd(t.reasons.map(e)))),jD=(e,t)=>e.load(t).pipe(AD(e=>dd(e)?hd(e.error).annotate(wd(e)):e),ym(n=>({provider:e,path:t,node:n,toString:kD}))),MD=(e,t)=>jD(e.provider,[...e.path,t]),ND=(e,t)=>Wy(Iv,e,new uv(rv(e=>t(e)),tv())),PD=e=>{switch(e._tag){case`Union`:return e.types.every(PD);case`Objects`:case`Arrays`:case`Suspend`:return!1;default:return!0}},FD=(e,t)=>{switch(e._tag){case`Objects`:return t?._tag===`Record`;case`Arrays`:return t?._tag===`Array`;case`Union`:return e.types.some(e=>FD(e,t));case`Suspend`:return FD(e.thunk(),t);default:return t?.value!==void 0}},ID=/*#__PURE__*/ Vt(e=>{let t=/* @__PURE__ */ new WeakSet,n=rae(e=>{switch(t.add(e),e._tag){case`Objects`:{let t=e.indexSignatures.map(e=>wb(e.parameter)),r=H(function*(n){if(n.node?._tag!==`Record`)return;let r=n.node,i=/* @__PURE__ */ new Set;for(let t of e.propertySignatures)typeof t.name==`string`&&i.add(t.name);if(t.length>0)for(let e of r.keys)t.some(t=>t(e))&&i.add(e);let a={};for(let e of i){let t=yield*MD(n,e);t.node!==void 0&&or(a,e,t)}return a});return ND(e.recur(n,e=>e),r)}case`Arrays`:{let t=H(function*(e){if(e.node?._tag!==`Array`)return;let t=[];for(let n=0;n<e.node.length;n++)t.push(yield*MD(e,n));return t});return ND(e.recur(n),t)}case`Union`:for(let t of e.types)n(t);if(!PD(e))return e.recur(n);break;case`Suspend`:{let r=e.thunk();return t.has(r)||n(r),e.recur(n)}case`Declaration`:case`Any`:throw new globalThis.Error(`Config.schema does not support opaque StringTree encodings`,{cause:e})}return ND(e,e=>F(e.node?.value))});return n(e)});function LD(e,t){let n=KS(e),r=Jy(n.ast),i=Tb(Ax(ID(n.ast))),a=typeof t==`string`?[t]:t??[];return TD((e,t)=>{let n=[...t,...a];return jD(e,n).pipe(Sm(e=>i(e).pipe(ym(ba),Cm(t=>{let i=new CD(new yx(n.length>0?new b_(n,t):t));return FD(r,e.node)?z(i):F(xa(i))}))),AD(e=>ire(e)&&OD(e.defect)?md(new CD(e.defect)).annotate(wd(e)):e))})}const RD=/*#__PURE__*/ dS.check(/*#__PURE__*/ uS({minimum:1,maximum:65535})),zD=e=>Jt(e)||globalThis.Array.isArray(e);function BD(e){return LD(U,e)}function VD(e,t,n){let r=zD(t),i=r?n:t,a=G(e),o=i?.separator??`,`;return LD(K([U.pipe($x(KS(a),{decode:bie(i),encode:X_(tv({strict:!1}),nv(e=>e.join(o)))})),a]),r?t:void 0)}function HD(e){return LD(zoe,e)}function UD(e){return LD(RD,e)}function WD(e){return LD(NS(U),e)}const GD=2**48-1,KD=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,qD=(e,t)=>{if(t.length!==10)throw Error(`ULID randomness must be exactly 10 bytes, received ${t.length}`);let n=Math.min(Math.max(0,Math.trunc(e)),GD),r=``;for(let e=45;e>=0;e-=5)r+=KD[Math.floor(n/2**e)&31];let i=0,a=0;for(let e of t){for(i=i<<8|e,a+=8;a>=5;)a-=5,r+=KD[i>>>a&31];i&=(1<<a)-1}return r},JD=e=>e.toString(16).padStart(2,`0`),YD=e=>[e.subarray(0,4),e.subarray(4,6),e.subarray(6,8),e.subarray(8,10),e.subarray(10,16)].map(e=>Array.from(e,JD).join(``)).join(`-`),XD=()=>globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));function ZD(e=XD()){return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e}const QD=2**48-1;function $D(e,t=XD()){let n=Math.min(Math.max(0,Math.trunc(e)),QD);return t[0]=Math.floor(n/2**40),t[1]=Math.floor(n/2**32)&255,t[2]=Math.floor(n/2**24)&255,t[3]=Math.floor(n/2**16)&255,t[4]=Math.floor(n/256)&255,t[5]=n&255,t[6]=t[6]&15|112,t[8]=t[8]&63|128,t}const eO=`~effect/Crypto`,tO=/*#__PURE__*/ P(`effect/Crypto`),nO=e=>{let t=e.randomBytes,n=e=>V(rO(`randomBytes`,e),t),r=e=>(e[0]&31)*2**48+e[1]*2**40+e[2]*2**32+e[3]*2**24+e[4]*2**16+e[5]*256+e[6],i=()=>r(t(7))/2**53,a=()=>{for(;;){let e=t(7),n=r(e);if(!(e[0]&32))return n+-(2**53-1);if(n<2**53-1)return n+1}};return tO.of({[eO]:eO,randomBytes:n,nextDoubleUnsafe:i,nextIntUnsafe:a,digest:e.digest,random:I(()=>i()),randomBoolean:I(()=>i()>.5),randomInt:I(()=>a()),randomBetween:(e,t)=>I(()=>Hre(e,t,i())),randomIntBetween(e,t,n){let r=n?.halfOpen===!0?0:1;return I(()=>{let n=Math.ceil(e),a=Math.floor(t);return Math.floor(i()*(a-n+r))+n})},randomShuffle:e=>I(()=>{let t=Array.from(e);for(let e=t.length-1;e>=1;--e){let n=Math.min(e,Math.floor(i()*(e+1))),r=t[e];t[e]=t[n],t[n]=r}return t}),randomUUIDv4:e=>I(()=>{let n=ZD(t(16));return e?.format===`bytes`?n:YD(n)}),randomUUIDv7:e=>dm(n=>{let r=$D(n.currentTimeMillisUnsafe(),t(16));return F(e?.format===`bytes`?r:YD(r))}),randomULID:dm(e=>F(qD(e.currentTimeMillisUnsafe(),t(10))))})},rO=(e,t)=>Number.isSafeInteger(t)&&t>=0?F(t):z(NT({module:`Crypto`,method:e,description:`size must be a non-negative safe integer`})),iO=e=>ap(t=>(cd(t,e),L)),aO=`~effect/ErrorReporter/ignore`,oO=`~effect/Match/Matcher`,sO={[oO]:{_input:M,_filters:M,_remaining:M,_result:M,_return:M,_args:M},_tag:`TypeMatcher`,add(e){return cO(this.select,[...this.cases,e])},pipe(){return jt(this,arguments)}};function cO(e,t){let n=Object.create(sO);return n.select=e,n.cases=t,n}const lO={[oO]:{_input:M,_filters:M,_result:M,_return:M,_flavor:M},_tag:`ValueMatcher`,add(e){return wa(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?uO(this.provided,ba(e.evaluate(this.provided))):this},pipe(){return jt(this,arguments)}};function uO(e,t){let n=Object.create(lO);return n.provided=e,n.value=t,n}const dO=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),fO=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(fO),n=t.length;return e=>{if(!Array.isArray(e))return!1;for(let r=0;r<n;r++)if(t[r](e[r])===!1)return!1;return!0}}if(typeof e==`object`&&e){let t=Reflect.ownKeys(e).map(t=>[t,fO(e[t])]),n=t.length;return e=>{if(typeof e!=`object`||!e)return!1;for(let r=0;r<n;r++){let[n,i]=t[r];if(!(n in e)||i(e[n])===!1)return!1}return!0}}return t=>t===e},pO=()=>cO(M,[]),mO=e=>uO(e,xa(e)),hO=(e,t)=>n=>n.add(dO(fO(e),t)),gO=e=>(...t)=>{let n=t[t.length-1],r=t.slice(0,-1),i=r.length===1?t=>t!=null&&t[e]===r[0]:t=>t!=null&&r.includes(t[e]);return e=>e.add(dO(i,n))},_O=e=>t=>{let n=dO(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},vO=/*#__PURE__*/ gO(`_tag`),yO=/*#__PURE__*/ _O(`_tag`),bO=(...e)=>{let t=e.length;return n=>{for(let r=0;r<t;r++)if(n===e[r])return!0;return!1}},xO=e=>t=>{let n=SO(t);return Sa(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return wa(r)?r.success:e(r.failure,...t)}},SO=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?ba(t.evaluate(r,...n)):xa(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return ba(t.evaluate(r,...n))}return xa(r)}},CO=`effect/match/Match/exhaustive: absurd`,wO=e=>{let t=SO(e);if(Sa(t)){if(wa(t))return t.success;throw Error(CO)}return(...e)=>{let n=t(...e);if(wa(n))return n.success;throw Error(CO)}},TO=pO,EO=mO,DO=hO,OO=vO,kO=yO,AO=bO,jO=Jt,MO=Yt,NO=Xt,PO=xO,FO=wO,IO={"~effect/Ref":{_A:M},...vr,toJSON(){return{_id:`Ref`,ref:this.ref}}},LO=e=>{let t=Object.create(IO);return t.ref=iC(e),t},RO=e=>I(()=>LO(e)),zO=e=>I(()=>e.ref.current),BO=/*#__PURE__*/ j(2,(e,t)=>I(()=>aC(e.ref,t))),VO=/*#__PURE__*/ j(2,(e,t)=>e===void 0?void 0:t(e)),HO=`~effect/Stdio`,UO=/*#__PURE__*/ P(HO),WO=e=>({[HO]:HO,stdinIsTerminal:F(!1),stdoutIsTerminal:F(!1),stderrIsTerminal:F(!1),...e}),GO=`~effect/Terminal`,KO=`~effect/Terminal/QuitError`;var qO=class extends (/*#__PURE__*/ HS(`QuitError`)({_tag:/*#__PURE__*/ tS(`QuitError`)})){[KO]=KO};const JO=/*#__PURE__*/ P(`effect/Terminal`),YO=e=>JO.of({...e,[GO]:GO}),XO=/*#__PURE__*/ YS(),ZO=/*#__PURE__*/ YS(),QO=`~effect/process/ChildProcessSpawner/ChildProcessHandle`,$O={[QO]:QO,...er,toJSON(){return{_id:`ChildProcessHandle`,pid:this.pid}}},ek=e=>Object.setPrototypeOf({...e},$O),tk=e=>{let t=(t,n)=>e(t).pipe(V(e=>BE(n?.includeStderr===!0?e.all:e.stdout)),DE),n=(e,n)=>HE(t(e,n));return nk.of({spawn:e,exitCode:t=>zp(B(e(t),e=>e.exitCode)),streamString:t,streamLines:n,lines:(e,t)=>KE(n(e,t)),string:(e,n)=>YE(t(e,n))})};var nk=class extends (/*#__PURE__*/ P()(`effect/process/ChildProcessSpawner`)){};const rk=`~effect/process/ChildProcess`,ik={.../*#__PURE__*/ ii({label:`Command`,evaluate(e){return ua(e.context,nk).spawn(this)}}),[rk]:rk},ak=(e,t,n)=>Object.assign(Object.create(ik),{_tag:`StandardCommand`,command:e,args:t,options:n}),ok=function(...e){if(sk(e[0])){let[t,...n]=e,r=uk(t,n);return ak(r[0]??``,r.slice(1),{})}if(typeof e[0]==`object`&&!Array.isArray(e[0])&&!sk(e[0])){let t=e[0];return function(e,...n){let r=uk(e,n);return ak(r[0]??``,r.slice(1),t)}}if(typeof e[0]==`string`&&!Array.isArray(e[1])){let[t,n={}]=e;return ak(t,[],n)}let[t,n=[],r={}]=e;return ak(t,n,r)},sk=e=>Array.isArray(e)&&`raw`in e&&Array.isArray(e.raw),ck=e=>{let t=/^fd(\d+)$/.exec(e);if(t===null)return;let n=parseInt(t[1],10);return n>=3?n:void 0},lk=e=>`fd${e}`,uk=(e,t)=>{let n=[];for(let[r,i]of e.entries())n=dk(e,t,n,i,r);return n},dk=(e,t,n,r,i)=>{let a=e.raw[i];if(a===void 0)throw Error(`Invalid backslash sequence: ${e.raw[i]}`);let{hasLeadingWhitespace:o,hasTrailingWhitespace:s,tokens:c}=hk(r,a),l=gk(n,c,o);if(i===t.length)return l;let u=t[i],d=Array.isArray(u)?u.map(e=>fk(e)):[fk(u)];return gk(l,d,s)},fk=e=>typeof e==`string`?e:String(e),pk=/*#__PURE__*/ new Set([` `,` `,`\r`,`
|
|
21
|
+
`]),mk={x:3,u:5},hk=(e,t)=>{if(t.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let n=pk.has(t[0]),r=[],i=0;for(let n=0,a=0;n<e.length;n+=1,a+=1){let o=t[a];if(pk.has(o))i!==n&&r.push(e.slice(i,n)),i=n+1;else if(o===`\\`){let e=t[a+1];if(e===`
|
|
22
|
+
`)--n,a+=1;else if(e===`u`&&t[a+2]===`{`){let e=t.indexOf(`}`,a+3);parseInt(t.slice(a+3,e),16)>65535&&(n+=1),a=e}else a+=mk[e]??1}}let a=i===e.length;return a||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:a}},gk=(e,t,n)=>n||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e.at(-1)}${t.at(0)}`,...t.slice(1)],_k=(e,t,n)=>{let r=e.detached??n!==`win32`;return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}},vk=(e,t)=>(n,[r])=>{let i=`Unknown`;switch(n.code){case`ENOENT`:i=`NotFound`;break;case`EACCES`:i=`PermissionDenied`;break;case`EEXIST`:i=`AlreadyExists`;break;case`EISDIR`:i=`BadResource`;break;case`ENOTDIR`:i=`BadResource`;break;case`EBUSY`:i=`Busy`;break;case`ELOOP`:i=`BadResource`}return MT({_tag:i,module:e,method:t,pathOrDescriptor:r,syscall:n.syscall,cause:n})},yk=e=>HT(eT(bk(e),e=>[e])),bk=e=>Pw(t=>{let n=e.evaluate();return F(xk({...e,writable:n,pull:t}))}),xk=e=>e.pull.pipe(B(t=>{let n=0;return $f(r=>{let i=!1,a=()=>{for(;n<t.length;){if(i)return;if(!e.writable.write(t[n++],e.encoding)){i||e.writable.once(`drain`,a);return}}i||r(L)};return a(),I(()=>{i=!0,e.writable.off(`drain`,a)})})}),Qp({disableYield:!0}),e.endOnDone===!1?M:If(t=>`closed`in e.writable&&e.writable.closed?Sd(t):$f(n=>{let r=()=>n(Sd(t));return e.writable.once(`finish`,r),e.writable.end(),I(()=>{e.writable.off(`finish`,r)})})),Ep($f(t=>{let n=n=>t(z(e.onError(n)));return e.writable.once(`error`,n),I(()=>{e.writable.off(`error`,n)})}))),Sk=e=>mE(Ck(e)),Ck=e=>Pw((t,n)=>Ok({scope:n,readable:e.evaluate(),onError:e.onError??kk,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),wk=e=>Pw((t,n)=>{let r=e.evaluate(),i=iC(void 0),a=eC(!1);return xk({pull:t,writable:r,onError:e.onError??kk,endOnDone:e.endOnDone,encoding:e.encoding}).pipe(hp(e=>(Lf(e)||(i.current=Od(e),a.openUnsafe()),L)),rm(n),B(()=>Ok({scope:n,exit:i,latch:a,readable:r,onError:e.onError??kk,chunkSize:e.chunkSize})))}),Tk=/*#__PURE__*/ j(2,(e,t)=>zE(e,wk(t))),Ek=(e,t)=>{let n=Ak(t?.maxBytes),r=t?.onError??kk;return $f(t=>{let i=e(),a=[],o=0;return i.once(`error`,e=>{`closed`in i&&!i.closed&&i.destroy(),t(z(r(e)))}),i.once(`end`,()=>{let e=a.length===1?a[0]:Buffer.concat(a);if(e.byteOffset===0&&e.buffer.byteLength===e.byteLength)return t(F(e.buffer));t(F(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)))}),i.on(`data`,e=>{a.push(e),o+=e.length,n!==void 0&&o>n&&(`closed`in i&&!i.closed&&i.destroy(),t(z(r(/* @__PURE__ */ Error(`maxBytes exceeded`)))))}),I(()=>{`closed`in i&&!i.closed&&i.destroy()})})},Dk=(e,t)=>V(Ek(e,t),e=>new Uint8Array(e)),Ok=e=>{let t=e.readable,n=e.closeOnDone??!0,r=e.exit??iC(void 0),i=e.latch??eC(!1);function a(){i.openUnsafe()}function o(t){r.current=kd(e.onError(t)),i.openUnsafe()}function s(){r.current=kd(xd()),i.openUnsafe()}t.on(`readable`,a),t.once(`error`,o),t.once(`end`,s);let c=Qf(function n(){let a=e.readable.read(e.chunkSize);if(a===null)return r.current?r.current:t.readableEnded?z(xd()):(i.closeUnsafe(),B(i.await,n));let o=Fa(a);for(;a=e.readable.read(e.chunkSize),a!==null;)o.push(a);return F(o)});return dp(Xd(e.scope,I(()=>{t.off(`readable`,a),t.off(`error`,o),t.off(`end`,s),n&&`closed`in e.readable&&!e.readable.closed&&e.readable.destroy()})),c)},kk=e=>new mre(e),Ak=e=>e===void 0||e===1/0?void 0:Number(oh(e)),jk=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),Mk=(e,t,n)=>{let{commands:r}=Rk(n),i=r.reduce((e,t)=>{let n=`${t.command} ${t.args.join(` `)}`;return e.length===0?n:`${e} | ${n}`},``);return vk(`ChildProcess`,e)(t,[i])},Nk=1e3,Pk=e=>{let t=()=>{};e.on(`error`,t),e.once(`close`,()=>e.off(`error`,t))},Fk=(e,t)=>{if(!Hd(t))return!0;if(globalThis.process.platform===`win32`)return!1;try{return globalThis.process.kill(-e.pid,0),!0}catch{return!1}},Ik=(e,t=()=>{})=>{e.exitCode!==null||e.signalCode!==null?t(null):yt.execFile(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{windowsHide:!0},t)},Lk=/*#__PURE__*/ pf(nk,/* @__PURE__ */ R(function*(){let e=yield*$E,t=yield*iD,n=H(function*(n){if(!en(n.cwd))return yield*e.access(n.cwd),t.resolve(n.cwd)}),r=e=>e.extendEnv?{...globalThis.process.env,...e.env}:e.env,i=e=>pE(e)?`pipe`:e,a=e=>VT(e)?`pipe`:e,o=e=>{let t={stream:`pipe`,encoding:`utf-8`,endOnDone:!0};return en(e.stdin)?t:typeof e.stdin==`string`||pE(e.stdin)?{...t,stream:e.stdin}:{stream:e.stdin.stream,encoding:e.stdin.encoding??t.encoding,endOnDone:e.stdin.endOnDone??t.endOnDone}},s=(e,t)=>{let n=e[t];return en(n)?{stream:`pipe`}:typeof n==`string`||VT(n)?{stream:n}:{stream:n.stream}},c=e=>{if(en(e.additionalFds))return[];let t=[];for(let[n,r]of Object.entries(e.additionalFds)){let e=ck(n);tn(e)&&t.push({fd:e,config:r})}return t.sort((e,t)=>e.fd-t.fd)},l=(e,t,n,r)=>{let o=[i(e.stream),a(t.stream),a(n.stream)];if(r.length===0)return o;let s=r.reduce((e,{fd:t})=>Math.max(e,t),2);for(let e=3;e<=s;e++)o[e]=`ignore`;for(let{fd:e}of r)o[e]=`pipe`;return o},u=H(function*(e,t,n){if(n.length===0)return{getInputFd:()=>GT,getOutputFd:()=>xE};let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let{config:a,fd:o}of n){let n=t.stdio[o];switch(a.type){case`input`:{let t=GT;n&&`write`in n&&(Pk(n),t=yk({evaluate:()=>n,onError:t=>Mk(`fromWritable(fd${o})`,jk(t),e)})),a.stream&&(yield*im(GE(a.stream,t))),r.set(o,t);break}case`output`:{let t=xE;if(n&&`read`in n){let r=new xt;n.on(`error`,e=>r.destroy(e)),n.pipe(r),t=Sk({evaluate:()=>r,onError:t=>Mk(`fromReadable(fd${o})`,jk(t),e)})}a.sink&&(t=RE(t,a.sink)),i.set(o,t);break}}}return{getInputFd:e=>r.get(e)??GT,getOutputFd:e=>i.get(e)??xE}}),d=(e,t,n)=>Qf(()=>{let r=GT;return nn(t.stdin)&&(Pk(t.stdin),r=yk({evaluate:()=>t.stdin,onError:t=>Mk(`fromWritable(stdin)`,jk(t),e),endOnDone:n.endOnDone,encoding:n.encoding})),pE(n.stream)?dp(im(GE(n.stream,r)),r):F(r)}),f=(e,t,n,r)=>{let i=t.stdout?(()=>{let n=new xt;return t.stdout.on(`error`,e=>n.destroy(e)),t.stdout.pipe(n),Sk({evaluate:()=>n,onError:t=>Mk(`fromReadable(stdout)`,jk(t),e)})})():xE,a=t.stderr?(()=>{let n=new xt;return t.stderr.on(`error`,e=>n.destroy(e)),t.stderr.pipe(n),Sk({evaluate:()=>n,onError:t=>Mk(`fromReadable(stderr)`,jk(t),e)})})():xE;VT(n.stream)&&(i=RE(i,n.stream)),VT(r.stream)&&(a=RE(a,r.stream));let o=NE(i,a);return{stdout:i,stderr:a,all:o}},p=(e,t)=>$f(n=>{let r=Ld(),i=yt.spawn(e.command,e.args,t);return i.on(`error`,t=>{n(z(Mk(`spawn`,t,e)))}),i.on(`exit`,(...e)=>{Wd(r,Dd(e))}),i.on(`spawn`,()=>{n(F([i,r]))}),I(()=>{i.kill(`SIGTERM`)})}),m=(e,t,n)=>globalThis.process.platform===`win32`?$f(n=>{Ik(t,t=>{n(t?z(Mk(`kill`,jk(t),e)):L)})}):ip({try:()=>{globalThis.process.kill(-t.pid,n)},catch:t=>Mk(`kill`,jk(t),e)}),h=(e,t)=>{if(globalThis.process.platform===`win32`)Ik(e);else try{globalThis.process.kill(-e.pid,t)}catch{}},g=(e,t,n)=>Qf(()=>{if(!t.kill(n)){let t=new globalThis.Error(`Failed to kill child process`);return z(Mk(`kill`,t,e))}return L}),_=(e,t,n)=>$f(r=>{let i=Date.now()+n,a,o=()=>{clearTimeout(a),e.removeListener(`exit`,s)},s=()=>{clearTimeout(a),Date.now()>=i||!Fk(e,t)?(o(),r(L)):a=setTimeout(s,10)};return e.on(`exit`,s),s(),I(o)}),v=H(function*(e,t,n,r){let i=n=>m(e,t,n).pipe(pp(()=>g(e,t,n)));yield*i(r?.killSignal??`SIGTERM`),en(r?.forceKillAfter)?yield*_(t,n,Nk):(yield*_(t,n,_o(r.forceKillAfter)),Fk(t,n)&&(yield*i(`SIGKILL`),yield*_(t,n,Nk))),yield*zd(n)}),y=(e,t)=>{let n=t??`stdout`;switch(n){case`stdout`:return e.stdout;case`stderr`:return e.stderr;case`all`:return e.all;default:{let t=ck(n);return tn(t)?e.getOutputFd(t):e.stdout}}},b=H(function*(e){switch(e._tag){case`StandardCommand`:{let t=o(e.options),i=s(e.options,`stdout`),a=s(e.options,`stderr`),m=c(e.options),g=!0,_=yield*n(e.options),y=r(e.options),b=l(t,i,a,m),[x,S]=yield*Bp(p(e,_k(e.options,{cwd:_,env:y,stdio:b},process.platform)),H(function*([t,n]){if(yield*Vd(n)){let[r]=yield*zd(n);(r!==0&&nn(r)||g&&process.platform!==`win32`&&e.options.detached!==!1)&&(yield*Sp(v(e,t,n,e.options)))}else g&&(yield*Sp(v(e,t,n,e.options)))})),ee=ZO(x.pid);x.on(`exit`,t=>{t!==0&&nn(t)&&h(x,e.options.killSignal??`SIGTERM`)});let C=I(()=>{g||=(x.ref(),!0)}),te=I(()=>(g&&=(x.unref(),!1),C)),w=yield*d(e,x,t),{all:ne,stderr:T,stdout:re}=f(e,x,i,a),{getInputFd:ie,getOutputFd:ae}=yield*u(e,x,m),oe=V(Vd(S),e=>!e),se=B(zd(S),([t,n])=>{if(nn(t))return F(XO(t));let r=new globalThis.Error(`Process interrupted due to receipt of signal: '${n}'`);return z(Mk(`exitCode`,r,e))});return ek({pid:ee,exitCode:se,isRunning:oe,kill:t=>v(e,x,S,t),stdin:w,stdout:re,stderr:T,all:ne,getInputFd:ie,getOutputFd:ae,unref:te})}case`PipedCommand`:{let{commands:t,pipeOptions:n}=Rk(e),[r,...i]=t,a=[yield*b(r)];for(let e=0;e<i.length;e++){let t=i[e],r=n[e]??{},s=o(t.options),c=DE(F(y(a[a.length-1],r.from))),l=r.to??`stdin`;if(l===`stdin`)a.push(yield*b(ok(t.command,t.args,{...t.options,stdin:{...s,stream:c}})));else{let e=ck(l);if(tn(e)){let n=lk(e),r=t.options.additionalFds??{};a.push(yield*b(ok(t.command,t.args,{...t.options,additionalFds:{...r,[n]:{type:`input`,stream:c}}})))}else a.push(yield*b(ok(t.command,t.args,{...t.options,stdin:{...s,stream:c}})))}}let s=a[a.length-1],c=e=>qf([...a].reverse(),t=>Sp(t.kill(e)),{discard:!0}),l=R(function*(){let e=[];for(let t of a)e.push(yield*t.unref);return qf([...e].reverse(),e=>e,{discard:!0})});return ek({pid:s.pid,exitCode:s.exitCode,isRunning:s.isRunning,kill:c,stdin:a[0].stdin,stdout:s.stdout,stderr:s.stderr,all:s.all,getInputFd:s.getInputFd,getOutputFd:s.getOutputFd,unref:l})}}});return tk(b)})),Rk=e=>{let t=[],n=[],r=e=>{switch(e._tag){case`StandardCommand`:t.push(e);break;case`PipedCommand`:r(e.left),n.push(e.options),r(e.right)}};if(r(e),t.length===0)throw Error(`flattenCommand produced empty commands array`);let[i,...a]=t;return{commands:[i,...a],pipeOptions:n}},zk=`~effect/http/HttpBody`,Bk=`~effect/http/HttpBody/HttpBodyError`;var Vk=class extends (/*#__PURE__*/ Bo(`HttpBodyError`)){[Bk]=Bk},Hk=class{[zk];constructor(){this[zk]=zk}[Qn](){return this.toJSON()}toString(){return qn(this,{ignoreToString:!0})}};const Uk=/*#__PURE__*/ new class extends Hk{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}};var Wk=class extends Hk{_tag=`Raw`;body;contentType;contentLength;constructor(e,t,n){super(),this.body=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Raw`,body:this.body,contentType:this.contentType,contentLength:this.contentLength}}};const Gk=(e,t)=>new Wk(e,t?.contentType,t?.contentLength);var Kk=class extends Hk{_tag=`Uint8Array`;contentType;contentLength;text;_body;constructor(e,t,n,r){super(),this._body=e,this.text=r,this.contentType=t,this.contentLength=n}get body(){return this._body??=Xk(this.text)}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}};const qk=(e,t)=>new Kk(e,t??`application/octet-stream`,e.length),Jk=/*#__PURE__*/ new TextEncoder,Yk=globalThis.Buffer,Xk=Yk===void 0?e=>Jk.encode(e):e=>Yk.from(e,`utf8`),Zk=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),Yk!==void 0)return new Kk(void 0,t??`text/plain`,Yk.byteLength(e,`utf8`),e);let n=Jk.encode(e);return new Kk(n,t??`text/plain`,n.length,e)},Qk=(e,t)=>Zk(JSON.stringify(e),t??`application/json`),$k=(e,t)=>ip({try:()=>Zk(JSON.stringify(e),t??`application/json`),catch:e=>new Vk({reason:{_tag:`JsonError`},cause:e})}),eA=(e,t)=>{let n=Eb(GS(e));return(e,r)=>n(e,t).pipe(vp(e=>new Vk({reason:{_tag:`SchemaError`,issue:e},cause:e})),B(e=>$k(e,r)))};var tA=class extends Hk{_tag=`Stream`;stream;contentType;contentLength;constructor(e,t,n){super(),this.stream=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Stream`,contentType:this.contentType,contentLength:this.contentLength}}};const nA=(e,t,n)=>new tA(e,t??`application/octet-stream`,n),rA=`~effect/http/HttpClientError`;var iA=class extends (/*#__PURE__*/ Bo(`HttpClientError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[rA]=rA;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}};const aA=e=>e.endsWith(`Error`)?e.slice(0,-5):e,oA=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,sA=e=>`${e.method} ${Vg(e.url)}`;var cA=class extends (/*#__PURE__*/ Bo(`TransportError`)){get methodAndUrl(){return sA(this.request)}get message(){return oA(aA(this._tag),this.description,this.methodAndUrl)}},lA=class extends (/*#__PURE__*/ Bo(`InvalidUrlError`)){get methodAndUrl(){return sA(this.request)}get message(){return oA(aA(this._tag),this.description,this.methodAndUrl)}},uA=class extends (/*#__PURE__*/ Bo(`StatusCodeError`)){get methodAndUrl(){return sA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return oA(aA(this._tag),this.description,e)}},dA=class extends (/*#__PURE__*/ Bo(`DecodeError`)){get methodAndUrl(){return sA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return oA(aA(this._tag),this.description,e)}},fA=class extends (/*#__PURE__*/ Bo(`EmptyBodyError`)){get methodAndUrl(){return sA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return oA(aA(this._tag),this.description,e)}};const pA=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,mA=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],hA=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?bg(bg(e,`content-type`),`content-length`):(e=t.contentType===void 0?bg(e,`content-type`):_g(e,`content-type`,t.contentType),t.contentLength===void 0?bg(e,`content-length`):_g(e,`content-length`,t.contentLength.toString())),ese=e=>{if(e==null||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0};var tse=class extends (/*#__PURE__*/ Bo(`UrlError`)){};const gA=(e,t,n)=>ote({try:()=>{let r=new URL(e,nse());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Tg(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new tse({cause:e})}),nse=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},_A=`~effect/http/HttpClientRequest`,rse={[_A]:_A,...er,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Vg(this.url),urlParams:this.urlParams,hash:this.hash,headers:Un(this.headers),body:this.body.toJSON()}},pipe(){return jt(this,arguments)}};function vA(e,t,n,r,i,a){let o=Object.create(rse);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}const ise=/*#__PURE__*/ vA(`GET`,``,Fg,/*#__PURE__*/ Ai(),mg,Uk),yA=e=>(t,n)=>ose(ise,{method:e,url:t,...n??void 0}),ase=/*#__PURE__*/ yA(`GET`),bA=/*#__PURE__*/ yA(`POST`),ose=/*#__PURE__*/ j(2,(e,t)=>{let n=e;return t.method&&(n=sse(n,t.method)),t.url&&(n=use(n,t.url)),t.headers&&(n=xA(n,t.headers)),t.urlParams&&(n=dse(n,t.urlParams)),t.hash&&(n=fse(n,t.hash)),t.body&&(n=CA(n,t.body)),t.accept&&(n=SA(n,t.accept)),t.acceptJson&&(n=lse(n)),n}),sse=/*#__PURE__*/ j(2,(e,t)=>vA(t,e.url,e.urlParams,e.hash,e.headers,e.body)),cse=/*#__PURE__*/ j(3,(e,t,n)=>vA(e.method,e.url,e.urlParams,e.hash,_g(e.headers,t,n),e.body)),xA=/*#__PURE__*/ j(2,(e,t)=>vA(e.method,e.url,e.urlParams,e.hash,vg(e.headers,t),e.body)),SA=/*#__PURE__*/ j(2,(e,t)=>cse(e,`Accept`,t)),lse=/*#__PURE__*/ SA(`application/json`),use=/*#__PURE__*/ j(2,(e,t)=>{if(typeof t==`string`)return vA(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Ag(n.searchParams),i=Li(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,vA(e.method,n.toString(),r,i,e.headers,e.body)}),dse=/*#__PURE__*/ j(2,(e,t)=>vA(e.method,e.url,Ig(e.urlParams,t),e.hash,e.headers,e.body)),fse=/*#__PURE__*/ j(2,(e,t)=>vA(e.method,e.url,e.urlParams,ji(t),e.headers,e.body)),CA=/*#__PURE__*/ j(2,(e,t)=>vA(e.method,e.url,e.urlParams,e.hash,hA(e.headers,t),t)),wA=/*#__PURE__*/ j(2,(e,t)=>CA(e,Qk(t)));function pse(e){let t=gA(e.url,e.urlParams,zi(e.hash));return wa(t)?ji(t.success):Ai()}const TA=`~effect/http/HttpIncomingMessage`,EA=(e,t)=>{let n=wx(GS(e)),r=t?.reviver===void 0?void 0:wx(bS(GS(e),t));return e=>r===void 0?B(e.json,e=>n(e,t)):B(e.text,i=>i===``?B(e.json,e=>n(e,t)):r(i,t))},DA=/*#__PURE__*/ _a(`effect/http/HttpIncomingMessage/MaxBodySize`,{defaultValue:()=>void 0}),OA=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=cm(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=cm(e.text)}catch{}let i={...t,headers:Un(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},kA=`~effect/http/HttpClientResponse`,mse=(e,t)=>new hse(e,t);var hse=class extends tr{[TA];[kA];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[TA]=TA,this[kA]=kA}toJSON(){return OA(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split(`#`)[0];let e=pse(this.request);return Mi(e)?``:(e.value.hash=``,e.value.href)}get headers(){return hg(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Lh(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return Ai()}get stream(){return this.source.body?EE({evaluate:()=>this.source.body,onError:e=>new iA({reason:new dA({request:this.request,response:this,cause:e})})}):CE(new iA({reason:new fA({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return B(this.text,e=>ip({try:()=>e===``?null:JSON.parse(e),catch:e=>new iA({reason:new dA({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=V(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return B(this.text,e=>ip({try:()=>Ag(new URLSearchParams(e)),catch:e=>new iA({reason:new dA({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Xf({try:()=>this.source.formData(),catch:e=>new iA({reason:new dA({request:this.request,response:this,cause:e})})}).pipe(Kp,cm)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Xf({try:()=>this.source.arrayBuffer(),catch:e=>new iA({reason:new dA({request:this.request,response:this,cause:e})})}).pipe(Kp,cm),this.arrayBufferBody}pipe(){return jt(this,arguments)}};const gse=e=>gg({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${Pi(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),_se=e=>{let t=Sse(e);return Ni(t)||(t=vse(e),Ni(t))?t:yse(e)},vse=e=>{if(!(`b3`in e))return Ai();let t=e.b3.split(`-`);return t.length<2||jA(t[0],t[1])===!1?Ai():ji(Qo({traceId:t[0],spanId:t[1],sampled:!t[2]||t[2]===`1`||t[2]===`d`}))},yse=e=>!e[`x-b3-traceid`]||!e[`x-b3-spanid`]||jA(e[`x-b3-traceid`],e[`x-b3-spanid`])===!1?Ai():ji(Qo({traceId:e[`x-b3-traceid`],spanId:e[`x-b3-spanid`],sampled:e[`x-b3-flags`]===`1`||!e[`x-b3-sampled`]||e[`x-b3-sampled`]===`1`||e[`x-b3-sampled`]===`true`})),bse=/^[0-9a-f]{32}$/i,AA=/^[0-9a-f]{16}$/i,xse=/^(?:[0-9a-f]{16}|[0-9a-f]{32})$/i,jA=(e,t)=>xse.test(e)&&AA.test(t),Sse=e=>{if(!e.traceparent)return Ai();let t=e.traceparent.split(`-`);if(t.length!==4)return Ai();let[n,r,i,a]=t;switch(n){case`00`:return bse.test(r)===!1||AA.test(i)===!1||r===`00000000000000000000000000000000`||i===`0000000000000000`?Ai():ji(Qo({traceId:r,spanId:i,sampled:(parseInt(a,16)&1)==1}));default:return Ai()}},Cse={"http:":80,"https:":443,"ws:":80,"wss:":443},MA=(e,t,n)=>{let r=Vg(t.search,n).slice(1);if(e.attribute(`url.full`,Vg(t.href,n)),e.attribute(`url.path`,t.pathname),r!==``&&e.attribute(`url.query`,r),e.attribute(`url.scheme`,t.protocol.slice(0,-1)),t.hostname!==``){e.attribute(`server.address`,t.hostname.startsWith(`[`)?t.hostname.slice(1,-1):t.hostname);let n=t.port===``?Cse[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},wse=(e,t)=>{let n=e.params.filter(([,e])=>typeof e!=`string`).map(([e])=>e);return n.length===0?t:[...t,...new URLSearchParams(n.map(e=>[e,``])).keys()]},NA=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Cg(a,i)?`<redacted>`:n[a])},PA=`~effect/http/HttpClient`,FA=/*#__PURE__*/ P(`effect/HttpClient`),Tse=/*#__PURE__*/ j(2,(e,t)=>IA(B(n=>t(e.postprocess(F(n)),n)),e.preprocess)),Ese=/*#__PURE__*/ j(2,(e,t)=>IA(n=>t(e.postprocess(n)),e.preprocess)),IA=(e,t)=>{let n=Object.create(Dse);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},Dse={[PA]:PA,pipe(){return jt(this,arguments)},...er,toJSON(){return{_id:`effect/HttpClient`}},.../*#__PURE__*/ Object.fromEntries(/*#__PURE__*/ mA.map(([e,t])=>[t,function(t,n){return this.execute(yA(e)(t,n))}]))},Ose=e=>IA(t=>B(t,t=>ap(n=>{let r=RA.get(t),i=r??new AbortController,a=gA(t.url,t.urlParams,zi(t.hash));if(Ca(a))return z(new iA({reason:new lA({request:t,cause:a.failure})}));let o=a.success;if(n.getRef($o)||n.getRef(jse)(t)){let a=e(t,o,i.signal,n);return r?a:Zp(e=>Op(e(a),{onSuccess(e){return LA.register(e,i),F(new zA(e,i))},onFailure(e){return yd(e)&&i.abort(),tp(e)}}))}return $p(n.getRef(Pse)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(wg);MA(a,o,wse(t.urlParams,n.getRef(Yg)));let c=n.getRef(Mse);return NA(a,`request`,t.headers,c,s),t=n.getRef(Nse)?xA(t,gse(a)):t,Zp(l=>l(e(t,o,i.signal,n)).pipe(tm(a,{captureStackTrace:!1}),Op({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),NA(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),kse(n,a,t,e)),r?F(e):(LA.register(e,i),F(new zA(e,i)))),onFailure(e){return!r&&yd(e)&&i.abort(),tp(e)}})))})})),F),kse=(e,t,n,r)=>{let i=nr();rr(0);let a;try{a=kd(new iA({reason:new uA({request:n,response:r})}))}finally{rr(i)}t.end(e.getRef(Sre)?e.getRef(Tf).currentTimeNanosUnsafe():BigInt(0),a)},Ase=e=>Tse(e,(e,t)=>{let n=new AbortController;return RA.set(t,n),sp(Vp(()=>I(()=>n.abort())),e)}),jse=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>It}),Mse=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>It}),Nse=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:Ft}),Pse=/*#__PURE__*/ _a(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),Fse=e=>pf(FA)(jp(t=>V(e,e=>Ese(e,Ip(e=>ha(t,e)))))),LA=/*#__PURE__*/ (()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=/*#__PURE__*/ new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=/*#__PURE__*/ new WeakMap;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),RA=/*#__PURE__*/ new WeakMap;var zA=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[kA]=kA;[TA]=TA;applyInterrupt(e){return Qf(()=>(LA.unregister(this.original),Yp(e,()=>I(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return SE(()=>(LA.unregister(this.original),UE(this.original.stream,I(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Qn](){return this.original[Qn]()}pipe(){return jt(this,arguments)}};const BA=/\+/g,VA=function(){};VA.prototype=/*#__PURE__*/ Object.create(null);function HA(e){let t=new VA;if(typeof e!=`string`)return t;let n=e.length,r=``,i=``,a=-1,o=-1,s=!1,c=!1,l=!1,u=!1,d=!1,f=0;for(let p=0;p<n+1;p++)if(f=p===n?38:e.charCodeAt(p),f===38){if(d=o>a,d||(o=p),r=e.slice(a+1,o),d||r.length>0){if(l&&(r=r.replace(BA,` `)),s)try{r=decodeURIComponent(r)||r}catch{}if(d&&(i=e.slice(o+1,p),u&&(i=i.replace(BA,` `)),c))try{i=decodeURIComponent(i)||i}catch{}let n=t[r];n===void 0?t[r]=i:n.pop?n.push(i):t[r]=[n,i]}i=``,a=p,o=p,s=!1,c=!1,l=!1,u=!1}else f===61?o<=a?o=p:c=!0:f===43?o>a?u=!0:l=!0:f===37&&(o>a?c=!0:s=!0);return t}const Ise=/^https?:\/\/.*?\//,UA=/(\/:[^/()]*?)\?(\/?)/,Lse=[],Rse=/^[^:*(]*\/:[^/:*(.-]+$/,zse=e=>Rse.test(e),Bse=(e={})=>new Vse(e);var Vse=class{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees=/*#__PURE__*/ Object.create(null);staticRoutes=/*#__PURE__*/ Object.create(null);singleParamRoutes=/*#__PURE__*/ Object.create(null);singleParamDisabled=/*#__PURE__*/ Object.create(null);brothersNodesStack=[];singleParamArray=[``];on(e,t,n){let r=t.match(UA);if(r&&r.index!==void 0){Gse(t.length===r.index+r[0].length,`Optional Parameter needs to be the last parameter of the path`);let i=t.replace(UA,`$1$2`),a=t.replace(UA,`$2`)||`/`;this.on(e,i,n),this.on(e,a,n);return}this.options.ignoreDuplicateSlashes&&(t=qA(t)),this.options.ignoreTrailingSlash&&(t=JA(t));let i=typeof e==`string`?[e]:e;for(let e of i)this._on(e,t,n)}all(e,t){this.on(Xse,e,t)}_on(e,t,n){this.trees[e]===void 0&&(this.trees[e]=new KA(`/`));let r=t;if(r===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new KA(``),this.trees[e].staticChildren[`/`]=t}let i=this.trees[e].prefix.length,a=this.trees[e],o=[];for(let e=0;e<=r.length;e++){if(r.charCodeAt(e)===58&&r.charCodeAt(e+1)===58){e++;continue}let t=r.charCodeAt(e)===58&&r.charCodeAt(e+1)!==58,n=r.charCodeAt(e)===42;if(t||n||e===r.length&&e!==i){let t=r.slice(i,e);this.options.caseSensitive||(t=t.toLowerCase()),t=t.split(`::`).join(`:`),t=t.split(`%`).join(`%25`),a=a.createStaticChild(t)}if(t){let t=!1,n=!0,s=``,c=[],l=``,u=e+1;for(let d=u;;d++){let f=r.charCodeAt(d),p=f===40,m=f===45||f===46,h=f===47||d===r.length;if(p||m||h){let f=r.slice(u,d);if(o.push(f),t=t||p||m,p){let e=YA(r,d),t=r.slice(d,e+1);c.push(qse(t)),d=e+1,n=!0}else c.push(n?`(.*?)`:`(${s}|(?:(?!${s}).)*)`),n=!1;let g=d;for(;d<r.length;d++){let e=r.charCodeAt(d);if(e===47)break;if(e===58){if(r.charCodeAt(d+1)===58)d++;else break}}let _=r.slice(g,d);if(_&&(_=_.split(`::`).join(`:`),_=_.split(`%`).join(`%25`),c.push(s=Jse(_))),u=d+1,l+=`()`+_,h||r.charCodeAt(d)===47||d===r.length){let n=t?l:_,o=r.slice(e,d);r=r.slice(0,e+1)+n+r.slice(d),e+=n.length;let s=t?RegExp(`^`+c.join(``)+`$`):void 0;a=a.createParametricChild(s,_,o),i=e+1;break}}}}else if(n&&(o.push(`*`),a=a.createWildcardChild(),i=e+1,e!==r.length-1))throw Error(`Wildcard must be the last character in the route`)}this.options.caseSensitive||(r=r.toLowerCase()),r===`*`&&(r=`/*`);for(let t of this.routes)if(t.method===e&&t.pattern===r)throw Error(`Method '${e}' already declared for route '${r}'`);let s={method:e,path:t,pattern:r,params:o,handler:n};if(this.routes.push(s),a.addRoute(s),o.length===0){let t=r.split(`::`).join(`:`).split(`%`).join(`%25`),n=this.staticRoutes[e]??=/* @__PURE__ */ new Map;n.has(t)||n.set(t,a.handlerStorage.unconstrainedHandler)}else if(zse(t)){if(this.singleParamDisabled[e]!==!0){let n=t.slice(0,t.indexOf(`:`));this.options.caseSensitive||(n=n.toLowerCase()),n=n.split(`%`).join(`%25`);let r=this.singleParamRoutes[e]??=/* @__PURE__ */ new Map;r.has(n)||r.set(n,a.handlerStorage.unconstrainedHandler)}}else/[(*]|[^/]:|:[^/]*[-.]/.test(t)&&(this.singleParamDisabled[e]=!0,delete this.singleParamRoutes[e])}has(e,t){let n=this.trees[e];if(n===void 0)return!1;let r=n.getStaticChild(t);return r!==void 0&&r.isLeafNode}find(e,t){let n=this.trees[e];if(n===void 0)return;let r=``,i=!1,a=t.charCodeAt(0)===47&&(t.length===1||t.charCodeAt(t.length-1)!==47);if(a)for(let e=1;e<t.length;e++){let n=t.charCodeAt(e);if(n===37||n===63||n===59||n===35||n>=65&&n<=90||n===47&&t.charCodeAt(e-1)===47){a=!1;break}}if(!a){t.charCodeAt(0)!==47&&(t=t.replace(Ise,`/`));let e;try{e=Yse(t),t=e.path,r=e.querystring,i=e.shouldDecodeParam}catch{return}this.options.ignoreDuplicateSlashes&&(t=qA(t)),this.options.ignoreTrailingSlash&&(t=JA(t))}let o=t;!a&&this.options.caseSensitive===!1&&(t=t.toLowerCase());let s=this.options.maxParamLength,c=this.staticRoutes[e];if(c!==void 0){let e=c.get(t);if(e!==void 0)return{handler:e.handler,params:e.createParams(Lse),searchParams:HA(r)}}let l=this.singleParamRoutes[e];if(l!==void 0){let e=t.lastIndexOf(`/`)+1,n=l.get(t.slice(0,e));if(n!==void 0&&t.length>e){let t=o.slice(e);if(i&&(t=ZA(t)),t.length<=s)return this.singleParamArray[0]=t,{handler:n.handler,params:n.createParams(this.singleParamArray),searchParams:HA(r)}}}let u=n.prefix.length,d=[],f=t.length,p=this.brothersNodesStack;for(p.length=0;;){if(u===f&&n.isLeafNode){let e=n.handlerStorage?.find();if(e!==void 0)return{handler:e.handler,params:e.createParams(d),searchParams:HA(r)}}let e=n.getNextNode(t,u,p,d.length);if(e===void 0){if(p.length===0)return;let t=p.pop();u=t.brotherPathIndex,d.splice(t.paramsCount),e=t.brotherNode}for(n=e;;){if(n._tag===`StaticNode`){u+=n.prefix.length;break}if(n._tag===`WildcardNode`){let e=o.slice(u);i&&(e=ZA(e)),d.push(e),u=f;break}let e=o.indexOf(`/`,u);e===-1&&(e=f);let t=o.slice(u,e);if(i&&(t=ZA(t)),n.regex!==void 0){let e=n.regex.exec(t);if(e===null){if(p.length===0)return;let e=p.pop();u=e.brotherPathIndex,d.splice(e.paramsCount),n=e.brotherNode;continue}let r=!1;for(let t=1;t<e.length;t++)if((e[t]??``).length>s){r=!0;break}if(r){if(p.length===0)return;let e=p.pop();u=e.brotherPathIndex,d.splice(e.paramsCount),n=e.brotherNode;continue}for(let t=1;t<e.length;t++)d.push(e[t]??``)}else{if(t.length>s){if(p.length===0)return;let e=p.pop();u=e.brotherPathIndex,d.splice(e.paramsCount),n=e.brotherNode;continue}d.push(t)}u=e;break}}}},Hse=class{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:Kse(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}},WA=class{isLeafNode=!1;routes;handlerStorage;addRoute(e){this.routes===void 0?this.routes=[e]:this.routes.push(e),this.handlerStorage===void 0&&(this.handlerStorage=new Hse),this.isLeafNode=!0,this.handlerStorage.add(e)}},GA=class extends WA{staticChildren=/*#__PURE__*/ Object.create(null);findStaticMatchingChild(e,t){let n=this.staticChildren[e.charAt(t)];if(n!==void 0&&n.matchPrefix(e,t))return n}getStaticChild(e,t=0){if(e.length===t)return this;let n=this.findStaticMatchingChild(e,t);if(n!==void 0)return n.getStaticChild(e,t+n.prefix.length)}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let n=e.charAt(0);return this.staticChildren[n]=new KA(e),this.staticChildren[n]}},KA=class e extends GA{_tag=`StaticNode`;constructor(e){super(),this.setPrefix(e)}prefix;matchPrefix;parametricChildren=[];wildcardChild;setPrefix(e){if(this.prefix=e,e.length===1)this.matchPrefix=(e,t)=>!0;else{let t=e.slice(1);this.matchPrefix=(e,n)=>e.startsWith(t,n+1)}}getParametricChild(e){if(e===void 0)return this.parametricChildren.find(e=>e.isRegex===!1);let t=e.source;return this.parametricChildren.find(e=>e.regex!==void 0&&e.regex.source===t)}createParametricChild(e,t,n){let r=this.getParametricChild(e);return r===void 0?(r=new Use(e,t,n),this.parametricChildren.push(r),this.parametricChildren.sort((e,t)=>e.isRegex?t.isRegex?e.staticSuffix===void 0?1:t.staticSuffix===void 0?-1:t.staticSuffix.endsWith(e.staticSuffix)?1:e.staticSuffix.endsWith(t.staticSuffix)?-1:0:-1:1),r):(r.nodePaths.add(n),r)}createWildcardChild(){return this.wildcardChild===void 0&&(this.wildcardChild=new Wse),this.wildcardChild}split(t,n){let r=this.prefix.slice(0,n),i=this.prefix.slice(n);this.setPrefix(i);let a=new e(r);return a.staticChildren[i.charAt(0)]=this,t.staticChildren[r.charAt(0)]=a,a}getNextNode(e,t,n,r){let i=this.findStaticMatchingChild(e,t),a=0;if(i===void 0){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],a=1}this.wildcardChild!==void 0&&n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let e=this.parametricChildren.length-1;e>=a;e--)n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.parametricChildren[e]});return i}},Use=class extends GA{_tag=`ParametricNode`;regex;staticSuffix;constructor(e,t,n){super(),this.regex=e,this.staticSuffix=t,this.isRegex=!!e,this.nodePaths=/* @__PURE__ */ new Set([n])}isRegex;nodePaths;getNextNode(e,t){return this.findStaticMatchingChild(e,t)}},Wse=class extends WA{_tag=`WildcardNode`;getNextNode(e,t,n,r){}};const Gse=(e,t)=>{if(!e)throw Error(t)};function qA(e){return e.indexOf(`//`)===-1?e:e.replace(/\/\/+/g,`/`)}function JA(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function Kse(e){let t=e.length;return t===0?()=>Object.create(null):function(n){let r=Object.create(null);for(let i=0;i<t;i++)r[e[i]]=n[i];return r}}function YA(e,t){let n=1;for(;t<e.length;)if(t++,e[t]===`\\`)t++;else if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t;throw TypeError(`Invalid regexp expression in "`+e+`"`)}function qse(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function Jse(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function XA(e,t){if(e===50)return t===53?`%`:t===51?`#`:t===52?`$`:t===54?`&`:t===66||t===98?`+`:t===67||t===99?`,`:t===70||t===102?`/`:void 0;if(e===51)return t===65||t===97?`:`:t===66||t===98?`;`:t===68||t===100?`=`:t===70||t===102?`?`:void 0;if(e===52&&t===48)return`@`}function Yse(e){let t=!1,n=!1,r=``;for(let i=1;i<e.length;i++){let a=e.charCodeAt(i);if(a===37){let r=e.charCodeAt(i+1),a=e.charCodeAt(i+2);XA(r,a)===void 0?t=!0:(n=!0,r===50&&a===53&&(t=!0,e=e.slice(0,i+1)+`25`+e.slice(i+1),i+=2),i+=2)}else if(a===63||a===59||a===35){r=e.slice(i+1),e=e.slice(0,i);break}}return{path:t?decodeURI(e):e,querystring:r,shouldDecodeParam:n}}function ZA(e){let t=e.indexOf(`%`);if(t===-1)return e;let n=``,r=t;for(let i=t;i<e.length;i++)if(e.charCodeAt(i)===37){if(i+2>=e.length)break;let t=XA(e.charCodeAt(i+1),e.charCodeAt(i+2));n+=e.slice(r,i)+t,r=i+3}return e.slice(0,t)+n+e.slice(r)}const Xse=/* @__PURE__ */ `ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),QA=Bse,$A=e=>{switch(e._tag){case`Weak`:return`W/"${e.value}"`;case`Strong`:return`"${e.value}"`}};var ej=class extends (/*#__PURE__*/ P()(`effect/http/Etag/Generator`)){};const tj=e=>{let t=Pi(e.mtime,{onNone:()=>`0`,onSome:e=>e.getTime().toString(16)});return`${e.size.toString(16)}-${t}`},nj=e=>`${e.size.toString(16)}-${e.lastModified.toString(16)}`,Zse=/*#__PURE__*/ uf(ej)({fromFileInfo(e){return I(()=>({_tag:`Strong`,value:tj(e)}))},fromFileWeb(e){return I(()=>({_tag:`Strong`,value:nj(e)}))}}),Qse=/*#__PURE__*/ uf(ej)({fromFileInfo(e){return I(()=>({_tag:`Weak`,value:tj(e)}))},fromFileWeb(e){return I(()=>({_tag:`Weak`,value:nj(e)}))}}),$se=/*#__PURE__*/ Object.getPrototypeOf(mg),ece=()=>Object.create($se),rj=`~effect/http/HttpServerResponse`,ij=e=>N(e,rj),aj=e=>bj({status:e?.status??204,statusText:e?.statusText,headers:e?.headers?hg(e.headers):void 0,cookies:e?.cookies}),oj=(e,t)=>{let n=gg({location:e.toString()});return bj({status:t?.status??302,statusText:t?.statusText,headers:t?.headers?yg(n,hg(t.headers)):n,cookies:t?.cookies??zh})},sj=(e,t)=>{let n=t?.headers?hg(t.headers):mg;return bj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??zh,body:qk(e,cj(t,n))})},cj=(e,t)=>{if(e?.contentType)return e.contentType;if(e?.headers)return t[`content-type`]},lj=(e,t)=>{let n=t?.headers?hg(t.headers):mg;return bj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??zh,body:Zk(e,cj(t,n))})},tce=(e,t)=>{let n=eA(e,t);return(e,t)=>{let r=t?.headers?hg(t.headers):mg;return V(n(e,cj(t,r)),e=>bj({status:t?.status??200,statusText:t?.statusText,headers:r,cookies:t?.cookies,body:e}))}},uj=(e,t)=>{let n=t?.headers?hg(t.headers):mg;return bj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:Qk(e,cj(t,n))})},nce=(e,t)=>{let n=t?.headers?hg(t.headers):mg;return bj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:Zk(Lg(Ag(e)),cj(t,n)??`application/x-www-form-urlencoded`)})},dj=(e,t)=>bj({status:t?.status??200,statusText:t?.statusText,headers:t?.headers&&hg(t.headers),cookies:t?.cookies,body:Gk(e,{contentType:t?.contentType,contentLength:t?.contentLength})}),fj=(e,t)=>{let n=t?.headers?hg(t.headers):mg;return bj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:nA(e,cj(t,n),t?.contentLength)})},pj=/*#__PURE__*/ j(3,(e,t,n)=>bj(e,_g(e.headers,t,n))),mj=/*#__PURE__*/ j(2,(e,t)=>bj({...e,headers:bg(e.headers,t)})),hj=/*#__PURE__*/ j(2,(e,t)=>bj(e,vg(e.headers,t))),gj=/*#__PURE__*/ j(e=>ij(e[0]),(e,t,n,r)=>V(op(Yh(e.cookies,t,n,r)),t=>bj({...e,cookies:t}))),_j=/*#__PURE__*/ j(2,(e,t)=>bj({...e,cookies:Jh(e.cookies,t)})),vj=/*#__PURE__*/ j(2,(e,t)=>bj({...e,body:t},hA(e.headers,t))),rce=/*#__PURE__*/ j(e=>ij(e[0]),(e,t,n)=>bj({...e,status:t,statusText:n??e.statusText})),ice=(e,t=!1)=>t||e.status===204||e.status===205||e.status===304,yj=(e,t)=>{for(let[n,r]of t)n===`set-cookie`?e.append(n,r):e.set(n,r);return e},ace=(e,t)=>{let n=new globalThis.Headers(e.headers);if(!Bh(e.cookies)){let t=$h(e.cookies);for(let e of t)n.append(`set-cookie`,e)}let r=e.body,i=ice(e),a=i||t?.withoutBody===!0;if(r._tag===`Raw`&&r.body instanceof Response){let t=r.body;if(!a){if(n.keys().next().done)return t;let e=new Response(t.body,t);return yj(e.headers,n),e}let o=i?e:t;return new Response(void 0,{status:o.status,statusText:o.statusText,headers:yj(new globalThis.Headers(t.headers),n)})}if(a)return r._tag===`Raw`&&oce(r.body)&&r.body.cancel().catch(Rt),new Response(void 0,{status:e.status,statusText:e.statusText,headers:n});switch(r._tag){case`Empty`:return new Response(void 0,{status:e.status,statusText:e.statusText,headers:n});case`Uint8Array`:return new Response(r.text??r.body,{status:e.status,statusText:e.statusText,headers:n});case`Raw`:return new Response(r.body,{status:e.status,statusText:e.statusText,headers:n});case`FormData`:return new Response(r.formData,{status:e.status,statusText:e.statusText,headers:n});case`Stream`:return new Response(XE(r.stream,t?.context??ia(),{signal:t?.signal}),{status:e.status,statusText:e.statusText,headers:n})}},oce=e=>typeof ReadableStream<`u`&&e instanceof ReadableStream,sce={...vr,[rj]:rj,[aO]:!0,toJSON(){return{_id:`HttpServerResponse`,status:this.status,statusText:this.statusText,headers:Un(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}},bj=(e,t)=>{let n=Object.create(sce);if(n.status=e.status,n.statusText=e.statusText,n.cookies=e.cookies??zh,n.body=e.body??Uk,n.body._tag!==`Empty`&&(n.body.contentType||n.body.contentLength!==void 0)){let r=t!==void 0,i=r?t:e.headers===void 0||e.headers===mg?ece():gg({...e.headers});n.body.contentType&&(!r||i[`content-type`]===void 0)&&(i[`content-type`]=n.body.contentType),n.body.contentLength!==void 0&&(!r||i[`content-length`]===void 0)&&(i[`content-length`]=n.body.contentLength.toString()),n.headers=i}else n.headers=t??e.headers??mg;return n},cce=e=>{let t=new globalThis.Headers(e.headers),n=t.getSetCookie();t.delete(`set-cookie`);let r=aj({status:e.status,statusText:e.statusText,headers:t,cookies:Lh(n)});if(e.body){let t=e.headers.get(`content-type`);r=vj(r,nA(EE({evaluate:()=>e.body,onError:e=>e}),t??void 0,ese(e.headers.get(`content-length`))))}return r},lce=(e,t)=>{let n=e.vary;if(n===void 0)return t;let r=n.split(`,`).map(e=>e.trim().toLowerCase());return r.includes(`*`)||r.includes(t.toLowerCase())?n:`${n}, ${t}`},uce=e=>({algorithms:e.algorithms,compressResponse(t,n,r){return V(e.compressResponse(t,n,r),e=>{if(e===t)return t;let r={"content-encoding":n,vary:lce(e.headers,`Accept-Encoding`)},i=e.headers.etag;return i!==void 0&&!i.startsWith(`W/`)&&(r.etag=`W/${i}`),hj(e,r)})}}),xj={"application/andrew-inset":[`ez`],"application/appinstaller":[`appinstaller`],"application/applixware":[`aw`],"application/appx":[`appx`],"application/appxbundle":[`appxbundle`],"application/atom+xml":[`atom`],"application/atomcat+xml":[`atomcat`],"application/atomdeleted+xml":[`atomdeleted`],"application/atomsvc+xml":[`atomsvc`],"application/atsc-dwd+xml":[`dwd`],"application/atsc-held+xml":[`held`],"application/atsc-rsat+xml":[`rsat`],"application/automationml-aml+xml":[`aml`],"application/automationml-amlx+zip":[`amlx`],"application/bdoc":[`bdoc`],"application/calendar+xml":[`xcs`],"application/ccxml+xml":[`ccxml`],"application/cdfx+xml":[`cdfx`],"application/cdmi-capability":[`cdmia`],"application/cdmi-container":[`cdmic`],"application/cdmi-domain":[`cdmid`],"application/cdmi-object":[`cdmio`],"application/cdmi-queue":[`cdmiq`],"application/cpl+xml":[`cpl`],"application/cu-seeme":[`cu`],"application/cwl":[`cwl`],"application/dash+xml":[`mpd`],"application/dash-patch+xml":[`mpp`],"application/davmount+xml":[`davmount`],"application/dicom":[`dcm`],"application/docbook+xml":[`dbk`],"application/dssc+der":[`dssc`],"application/dssc+xml":[`xdssc`],"application/ecmascript":[`ecma`],"application/emma+xml":[`emma`],"application/emotionml+xml":[`emotionml`],"application/epub+zip":[`epub`],"application/exi":[`exi`],"application/express":[`exp`],"application/fdf":[`fdf`],"application/fdt+xml":[`fdt`],"application/font-tdpfr":[`pfr`],"application/geo+json":[`geojson`],"application/gml+xml":[`gml`],"application/gpx+xml":[`gpx`],"application/gxf":[`gxf`],"application/gzip":[`gz`],"application/hjson":[`hjson`],"application/hyperstudio":[`stk`],"application/inkml+xml":[`ink`,`inkml`],"application/ipfix":[`ipfix`],"application/its+xml":[`its`],"application/java-archive":[`jar`,`war`,`ear`],"application/java-serialized-object":[`ser`],"application/java-vm":[`class`],"application/javascript":[`*js`],"application/json":[`json`,`map`],"application/json5":[`json5`],"application/jsonml+json":[`jsonml`],"application/ld+json":[`jsonld`],"application/lgr+xml":[`lgr`],"application/lost+xml":[`lostxml`],"application/mac-binhex40":[`hqx`],"application/mac-compactpro":[`cpt`],"application/mads+xml":[`mads`],"application/manifest+json":[`webmanifest`],"application/marc":[`mrc`],"application/marcxml+xml":[`mrcx`],"application/mathematica":[`ma`,`nb`,`mb`],"application/mathml+xml":[`mathml`],"application/mbox":[`mbox`],"application/media-policy-dataset+xml":[`mpf`],"application/mediaservercontrol+xml":[`mscml`],"application/metalink+xml":[`metalink`],"application/metalink4+xml":[`meta4`],"application/mets+xml":[`mets`],"application/mmt-aei+xml":[`maei`],"application/mmt-usd+xml":[`musd`],"application/mods+xml":[`mods`],"application/mp21":[`m21`,`mp21`],"application/mp4":[`*mp4`,`*mpg4`,`mp4s`,`m4p`],"application/msix":[`msix`],"application/msixbundle":[`msixbundle`],"application/msword":[`doc`,`dot`],"application/mxf":[`mxf`],"application/n-quads":[`nq`],"application/n-triples":[`nt`],"application/node":[`cjs`],"application/octet-stream":[`bin`,`dms`,`lrf`,`mar`,`so`,`dist`,`distz`,`pkg`,`bpk`,`dump`,`elc`,`deploy`,`exe`,`dll`,`deb`,`dmg`,`iso`,`img`,`msi`,`msp`,`msm`,`buffer`],"application/oda":[`oda`],"application/oebps-package+xml":[`opf`],"application/ogg":[`ogx`],"application/omdoc+xml":[`omdoc`],"application/onenote":[`onetoc`,`onetoc2`,`onetmp`,`onepkg`,`one`,`onea`],"application/oxps":[`oxps`],"application/p2p-overlay+xml":[`relo`],"application/patch-ops-error+xml":[`xer`],"application/pdf":[`pdf`],"application/pgp-encrypted":[`pgp`],"application/pgp-keys":[`asc`],"application/pgp-signature":[`sig`,`*asc`],"application/pics-rules":[`prf`],"application/pkcs10":[`p10`],"application/pkcs7-mime":[`p7m`,`p7c`],"application/pkcs7-signature":[`p7s`],"application/pkcs8":[`p8`],"application/pkix-attr-cert":[`ac`],"application/pkix-cert":[`cer`],"application/pkix-crl":[`crl`],"application/pkix-pkipath":[`pkipath`],"application/pkixcmp":[`pki`],"application/pls+xml":[`pls`],"application/postscript":[`ai`,`eps`,`ps`],"application/provenance+xml":[`provx`],"application/pskc+xml":[`pskcxml`],"application/raml+yaml":[`raml`],"application/rdf+xml":[`rdf`,`owl`],"application/reginfo+xml":[`rif`],"application/relax-ng-compact-syntax":[`rnc`],"application/resource-lists+xml":[`rl`],"application/resource-lists-diff+xml":[`rld`],"application/rls-services+xml":[`rs`],"application/route-apd+xml":[`rapd`],"application/route-s-tsid+xml":[`sls`],"application/route-usd+xml":[`rusd`],"application/rpki-ghostbusters":[`gbr`],"application/rpki-manifest":[`mft`],"application/rpki-roa":[`roa`],"application/rsd+xml":[`rsd`],"application/rss+xml":[`rss`],"application/rtf":[`rtf`],"application/sbml+xml":[`sbml`],"application/scvp-cv-request":[`scq`],"application/scvp-cv-response":[`scs`],"application/scvp-vp-request":[`spq`],"application/scvp-vp-response":[`spp`],"application/sdp":[`sdp`],"application/senml+xml":[`senmlx`],"application/sensml+xml":[`sensmlx`],"application/set-payment-initiation":[`setpay`],"application/set-registration-initiation":[`setreg`],"application/shf+xml":[`shf`],"application/sieve":[`siv`,`sieve`],"application/smil+xml":[`smi`,`smil`],"application/sparql-query":[`rq`],"application/sparql-results+xml":[`srx`],"application/sql":[`sql`],"application/srgs":[`gram`],"application/srgs+xml":[`grxml`],"application/sru+xml":[`sru`],"application/ssdl+xml":[`ssdl`],"application/ssml+xml":[`ssml`],"application/swid+xml":[`swidtag`],"application/tei+xml":[`tei`,`teicorpus`],"application/thraud+xml":[`tfi`],"application/timestamped-data":[`tsd`],"application/toml":[`toml`],"application/trig":[`trig`],"application/ttml+xml":[`ttml`],"application/ubjson":[`ubj`],"application/urc-ressheet+xml":[`rsheet`],"application/urc-targetdesc+xml":[`td`],"application/voicexml+xml":[`vxml`],"application/wasm":[`wasm`],"application/watcherinfo+xml":[`wif`],"application/widget":[`wgt`],"application/winhlp":[`hlp`],"application/wsdl+xml":[`wsdl`],"application/wspolicy+xml":[`wspolicy`],"application/xaml+xml":[`xaml`],"application/xcap-att+xml":[`xav`],"application/xcap-caps+xml":[`xca`],"application/xcap-diff+xml":[`xdf`],"application/xcap-el+xml":[`xel`],"application/xcap-ns+xml":[`xns`],"application/xenc+xml":[`xenc`],"application/xfdf":[`xfdf`],"application/xhtml+xml":[`xhtml`,`xht`],"application/xliff+xml":[`xlf`],"application/xml":[`xml`,`xsl`,`xsd`,`rng`],"application/xml-dtd":[`dtd`],"application/xop+xml":[`xop`],"application/xproc+xml":[`xpl`],"application/xslt+xml":[`*xsl`,`xslt`],"application/xspf+xml":[`xspf`],"application/xv+xml":[`mxml`,`xhvml`,`xvml`,`xvm`],"application/yang":[`yang`],"application/yin+xml":[`yin`],"application/zip":[`zip`],"application/zip+dotlottie":[`lottie`],"audio/3gpp":[`*3gpp`],"audio/aac":[`adts`,`aac`],"audio/adpcm":[`adp`],"audio/amr":[`amr`],"audio/basic":[`au`,`snd`],"audio/midi":[`mid`,`midi`,`kar`,`rmi`],"audio/mobile-xmf":[`mxmf`],"audio/mp3":[`*mp3`],"audio/mp4":[`m4a`,`mp4a`,`m4b`],"audio/mpeg":[`mpga`,`mp2`,`mp2a`,`mp3`,`m2a`,`m3a`],"audio/ogg":[`oga`,`ogg`,`spx`,`opus`],"audio/s3m":[`s3m`],"audio/silk":[`sil`],"audio/wav":[`wav`],"audio/wave":[`*wav`],"audio/webm":[`weba`],"audio/xm":[`xm`],"font/collection":[`ttc`],"font/otf":[`otf`],"font/ttf":[`ttf`],"font/woff":[`woff`],"font/woff2":[`woff2`],"image/aces":[`exr`],"image/apng":[`apng`],"image/avci":[`avci`],"image/avcs":[`avcs`],"image/avif":[`avif`],"image/bmp":[`bmp`,`dib`],"image/cgm":[`cgm`],"image/dicom-rle":[`drle`],"image/dpx":[`dpx`],"image/emf":[`emf`],"image/fits":[`fits`],"image/g3fax":[`g3`],"image/gif":[`gif`],"image/heic":[`heic`],"image/heic-sequence":[`heics`],"image/heif":[`heif`],"image/heif-sequence":[`heifs`],"image/hej2k":[`hej2`],"image/ief":[`ief`],"image/jaii":[`jaii`],"image/jais":[`jais`],"image/jls":[`jls`],"image/jp2":[`jp2`,`jpg2`],"image/jpeg":[`jpg`,`jpeg`,`jpe`],"image/jph":[`jph`],"image/jphc":[`jhc`],"image/jpm":[`jpm`,`jpgm`],"image/jpx":[`jpx`,`jpf`],"image/jxl":[`jxl`],"image/jxr":[`jxr`],"image/jxra":[`jxra`],"image/jxrs":[`jxrs`],"image/jxs":[`jxs`],"image/jxsc":[`jxsc`],"image/jxsi":[`jxsi`],"image/jxss":[`jxss`],"image/ktx":[`ktx`],"image/ktx2":[`ktx2`],"image/pjpeg":[`jfif`],"image/png":[`png`],"image/sgi":[`sgi`],"image/svg+xml":[`svg`,`svgz`],"image/t38":[`t38`],"image/tiff":[`tif`,`tiff`],"image/tiff-fx":[`tfx`],"image/webp":[`webp`],"image/wmf":[`wmf`],"message/disposition-notification":[`disposition-notification`],"message/global":[`u8msg`],"message/global-delivery-status":[`u8dsn`],"message/global-disposition-notification":[`u8mdn`],"message/global-headers":[`u8hdr`],"message/rfc822":[`eml`,`mime`,`mht`,`mhtml`],"model/3mf":[`3mf`],"model/gltf+json":[`gltf`],"model/gltf-binary":[`glb`],"model/iges":[`igs`,`iges`],"model/jt":[`jt`],"model/mesh":[`msh`,`mesh`,`silo`],"model/mtl":[`mtl`],"model/obj":[`obj`],"model/prc":[`prc`],"model/step":[`step`,`stp`,`stpnc`,`p21`,`210`],"model/step+xml":[`stpx`],"model/step+zip":[`stpz`],"model/step-xml+zip":[`stpxz`],"model/stl":[`stl`],"model/u3d":[`u3d`],"model/vrml":[`wrl`,`vrml`],"model/x3d+binary":[`*x3db`,`x3dbz`],"model/x3d+fastinfoset":[`x3db`],"model/x3d+vrml":[`*x3dv`,`x3dvz`],"model/x3d+xml":[`x3d`,`x3dz`],"model/x3d-vrml":[`x3dv`],"text/cache-manifest":[`appcache`,`manifest`],"text/calendar":[`ics`,`ifb`],"text/coffeescript":[`coffee`,`litcoffee`],"text/css":[`css`],"text/csv":[`csv`],"text/html":[`html`,`htm`,`shtml`],"text/jade":[`jade`],"text/javascript":[`js`,`mjs`],"text/jsx":[`jsx`],"text/less":[`less`],"text/markdown":[`md`,`markdown`],"text/mathml":[`mml`],"text/mdx":[`mdx`],"text/n3":[`n3`],"text/plain":[`txt`,`text`,`conf`,`def`,`list`,`log`,`in`,`ini`],"text/richtext":[`rtx`],"text/rtf":[`*rtf`],"text/sgml":[`sgml`,`sgm`],"text/shex":[`shex`],"text/slim":[`slim`,`slm`],"text/spdx":[`spdx`],"text/stylus":[`stylus`,`styl`],"text/tab-separated-values":[`tsv`],"text/troff":[`t`,`tr`,`roff`,`man`,`me`,`ms`],"text/turtle":[`ttl`],"text/uri-list":[`uri`,`uris`,`urls`],"text/vcard":[`vcard`],"text/vtt":[`vtt`],"text/wgsl":[`wgsl`],"text/xml":[`*xml`],"text/yaml":[`yaml`,`yml`],"video/3gpp":[`3gp`,`3gpp`],"video/3gpp2":[`3g2`],"video/h261":[`h261`],"video/h263":[`h263`],"video/h264":[`h264`],"video/iso.segment":[`m4s`],"video/jpeg":[`jpgv`],"video/jpm":[`*jpm`,`*jpgm`],"video/mj2":[`mj2`,`mjp2`],"video/mp2t":[`ts`,`m2t`,`m2ts`,`mts`],"video/mp4":[`mp4`,`mp4v`,`mpg4`],"video/mpeg":[`mpeg`,`mpg`,`mpe`,`m1v`,`m2v`],"video/ogg":[`ogv`],"video/quicktime":[`qt`,`mov`],"video/webm":[`webm`]};Object.freeze(xj);let Sj;const dce=()=>{if(Sj!==void 0)return Sj;let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(xj)){let a=/* @__PURE__ */ new Set;n.set(r,a);for(let n=0;n<i.length;n++){let o=i[n],s=o.startsWith(`*`);s&&(o=o.slice(1)),a.add(o),n===0&&t.set(r,o),s||e.set(o,r)}}return Sj={extensionToType:e,typeToExtension:t,typeToExtensions:n},Sj},Cj=e=>{if(typeof e!=`string`)return Ai();let t=e.replace(/^.*[/\\]/s,``).toLowerCase(),n=t.replace(/^.*\./s,``).toLowerCase(),r=t.length<e.length;return!(n.length<t.length-1)&&r?Ai():Ri(dce().extensionToType.get(n))};var wj=class extends (/*#__PURE__*/ P()(`effect/http/HttpPlatform`)){};const fce=/*#__PURE__*/ H(function*(e){let t=yield*$E,n=yield*ej;return wj.of({platform:e.platform,compression:uce(e.compression),fileResponse:H(function*(r,i){let a=yield*t.stat(r),o=yield*n.fromFileInfo(a),s=i?.offset===void 0?th:yield*Ej(i.offset,`offset`),c=s>a.size?a.size:s,l=a.size-c,u=i?.bytesToRead===void 0?void 0:yield*Ej(i.bytesToRead,`bytesToRead`),d=u===void 0||u>l?l:u,f=u===void 0?void 0:c+d,p=yield*Dj(c,`offset`),m=f===void 0?void 0:yield*Dj(f,`end`),h=_g(Tj(i),`etag`,$A(o));return Ni(a.mtime)&&(h[`last-modified`]=a.mtime.value.toUTCString()),e.fileResponse(r,i?.status??200,i?.statusText,h,p,m,d)}),fileWebResponse(t,r){return V(n.fromFileWeb(t),n=>{let i=yg(Tj(r),gg({etag:$A(n),"last-modified":new Date(t.lastModified).toUTCString()}));return e.fileWebResponse(t,r?.status??200,r?.statusText,i,r)})}})}),Tj=e=>{let t=e?.headers?hg(e.headers):mg;return e?.contentType?_g(t,`content-type`,e.contentType):t},Ej=(e,t)=>{let n=sh(e);return Ni(n)?F(n.value):z(NT({module:`HttpPlatform`,method:`fileResponse`,description:`Invalid ${t}: ${e}`}))},Dj=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)?F(n):z(NT({module:`HttpPlatform`,method:`fileResponse`,description:`${t} exceeds the safe integer range: ${e}`}))},Oj=`~effect/http/HttpServerRespondable`,kj=e=>N(e,Oj),pce=/*#__PURE__*/ aj({status:400}),mce=/*#__PURE__*/ aj({status:404}),hce=(e,t)=>ij(e)?F(e):kj(e)?hp(e[Oj](),()=>F(t)):hx(e)?F(pce):fre(e)?F(mce):F(t),gce=(e,t)=>ij(e)?F(e):kj(e)?hp(e[Oj](),()=>F(t)):F(t),Aj=`~effect/http/HttpServerError`;var jj=class extends (/*#__PURE__*/ Bo(`HttpServerError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[Aj]=Aj;stack=`${this.name}: ${this.message}`;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}[Oj](){return this.reason[Oj]()}get[aO](){return this.reason[`~effect/ErrorReporter/ignore`]??!1}get message(){return this.reason.message}},Mj=class extends (/*#__PURE__*/ Bo(`RequestParseError`)){[Oj](){return F(aj({status:400}))}get methodAndUrl(){return Fj(this.request)}get message(){return Ij(this._tag,this.description,this.methodAndUrl)}},_ce=class extends (/*#__PURE__*/ Bo(`RouteNotFound`)){[Oj](){return F(aj({status:404}))}[aO]=!0;get methodAndUrl(){return Fj(this.request)}get message(){return Ij(this._tag,this.description,this.methodAndUrl)}};const vce=e=>N(e,Aj);var Nj=class extends (/*#__PURE__*/ Bo(`ResponseError`)){[Oj](){return F(aj({status:500}))}get methodAndUrl(){return Fj(this.request)}get message(){let e=`${this._tag} (${this.response.status} ${this.methodAndUrl})`;return this.description?`${e}: ${this.description}`:e}},Pj=class extends (/*#__PURE__*/ P()(`effect/http/HttpServerError/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ oa(Td,{name:`ClientAbort`,stack:Lt,parent:void 0}))};const Fj=e=>`${e.method} ${Vg(e.url)}`,Ij=(e,t,n)=>{let r=`${e} (${n})`;return t?`${r}: ${t}`:r},Lj=e=>{let t,n=bce,r=[],i=[],a=!1;for(let o=0;o<e.reasons.length;o++){let s=e.reasons[o];switch(s._tag){case`Fail`:n=hce(s.error,Rj),r.push(s);break;case`Die`:ij(s.defect)?t=s.defect:(n=gce(s.defect,Rj),r.push(s));break;case`Interrupt`:if(a=s.annotations.has(Pj.key),r.length>0)break;i.push(s)}}return t?F([t,fd(r)]):(i.length>0&&r.length===0&&(r.push(...i),n=a?xce:Sce),ym(n,e=>(r.push(hd(e)),[e,fd(r)])))},yce=e=>{let t,n=e.reasons.filter(e=>e._tag===`Die`&&ij(e.defect)?(t=e.defect,!1):!0);return[t??Rj,n.length>0?ji(fd(n)):Ai()]},Rj=/*#__PURE__*/ aj({status:500}),bce=/*#__PURE__*/ F(Rj),xce=/*#__PURE__*/ F(/*#__PURE__*/ aj({status:499})),Sce=/*#__PURE__*/ F(/*#__PURE__*/ aj({status:503})),zj=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,Bj=/\\([\v\u0020-\u{10ffff}])/gu,Cce=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,wce=/^[!#$%&'*+.^\w|~-]+$/u,Vj={value:``,parameters:/*#__PURE__*/ Object.create(null)};function Hj(e,t=!1){if(typeof e!=`string`)return Vj;let n=e.indexOf(`;`),r=n===-1?e.trim():e.slice(0,n).trim();if((t?wce:Cce).test(r)===!1)return Vj;let i={value:r.toLowerCase(),parameters:Object.create(null)};if(n===-1)return i;let a,o,s;for(zj.lastIndex=n;o=zj.exec(e);){if(o.index!==n)return Vj;n+=o[0].length,a=o[1].toLowerCase(),s=o[2],s[0]===`"`&&(s=s.slice(1,s.length-1),!t&&Bj.test(s)&&(s=s.replace(Bj,`$1`))),i.parameters[a]=s}return n===e.length?i:Vj}const Uj=16384,Wj={key:0,whitespace:1,value:2},Gj={_tag:`Continue`},Kj=/*#__PURE__*/ new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")Kj[/*#__PURE__*/ e.charCodeAt(0)]=1;const qj=/*#__PURE__*/ new Uint8Array(256);qj[9]=1;for(let e=32;e<=126;e++)qj[e]=1;for(let e=128;e<=255;e++)qj[e]=1;function Tce(){let e=new TextDecoder,t={state:Wj.key,headers:Object.create(null),key:``,value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function n(e){return t.state=Wj.key,t.headers=Object.create(null),t.key=``,t.value=void 0,t.crlf=0,t.previousChunk=void 0,t.pairs=0,t.size=0,e}function r(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function i(e){return n({_tag:`Failure`,reason:e,headers:t.headers})}return function(a,o){let s=0,c;if(t.previousChunk!==void 0){s=t.previousChunk.length,c=s;let e=new Uint8Array(a.length+s);e.set(t.previousChunk),e.set(a,s),t.previousChunk=void 0,a=e}let l=a.length;outer:for(;o<l;){if(t.state===Wj.key){let n=o;for(;n<l;n++){if(t.size++>Uj)return i(`HeaderTooLarge`);if(a[n]===58){if(t.key+=e.decode(a.subarray(o,n)).toLowerCase(),t.key.length===0)return i(`InvalidHeaderName`);a[n+1]===32&&a[n+2]!==32&&a[n+2]!==9?(o=n+2,t.state=Wj.value,t.size++):a[n+1]!==32&&a[n+1]!==9?(o=n+1,t.state=Wj.value):(o=n+1,t.state=Wj.whitespace);break}if(Kj[a[n]]!==1)return i(`InvalidHeaderName`)}if(n===l)return t.key+=e.decode(a.subarray(o,l)).toLowerCase(),Gj}if(t.state===Wj.whitespace){for(;o<l;o++){if(t.size++>Uj)return i(`HeaderTooLarge`);if(a[o]!==32&&a[o]!==9){t.state=Wj.value;break}}if(o===l)return Gj}if(t.state===Wj.value){let u=o;for(c!==void 0&&(u=c,c=void 0);u<l;u++){if(t.size++>Uj)return i(`HeaderTooLarge`);if(a[u]===13||t.crlf>0){let c=a[u];if(c===13&&t.crlf===0&&(t.crlf=1,u++,t.size++,c=a[u]),c===10&&t.crlf===1&&(t.crlf=2,u++,t.size++,c=a[u]),c===13&&t.crlf===2&&(t.crlf=3,u++,t.size++,c=a[u]),c===10&&t.crlf===3&&(t.crlf=4,u++,t.size++),t.crlf<4&&u>=l)return t.previousChunk=a.subarray(o),Gj;if(t.crlf>=2){t.value=t.value===void 0?a.subarray(o,u-t.crlf):r(t.value,a.subarray(o,u-t.crlf));let c=e.decode(t.value);if(t.headers[t.key]===void 0?t.headers[t.key]=c:typeof t.headers[t.key]==`string`?t.headers[t.key]=[t.headers[t.key],c]:t.headers[t.key].push(c),o=u,t.size--,t.crlf!==4&&t.pairs===100)return i(`TooManyHeaders`);if(t.crlf===3)return i(`InvalidHeaderValue`);if(t.crlf===4)return n({_tag:`Headers`,headers:t.headers,endPosition:o-s});t.pairs++,t.key=``,t.value=void 0,t.crlf=0,t.state=Wj.key;continue outer}}else if(qj[a[u]]!==1)return i(`InvalidHeaderValue`)}if(u===l)return t.value=t.value===void 0?a.subarray(o,l):r(t.value,a.subarray(o,l)),Gj}}return o>l&&(t.size+=l-o),Gj}}function Ece(e){let t=new TextEncoder().encode(e),n=t.length,r={};for(let e=0;e<n;e++){let n=t[e];r[n]===void 0&&(r[n]=[]),r[n].push(e)}return{needle:t,needleLength:n,indexes:r,firstByte:t[0],previousChunk:void 0,previousChunkLength:0,matchIndex:0}}function Dce(e,t,n,r){let i=Ece(e),a=r??i.needleLength;n!==void 0&&(i.previousChunk=n,i.previousChunkLength=n.length);function o(){if(`Buffer`in globalThis&&!(`Bun`in globalThis||`Deno`in globalThis))return function(e,t,n){return Buffer.prototype.indexOf.call(e,t,n)};let e=(/* @__PURE__ */ new Uint8Array(256)).fill(i.needle.length);for(let t=0,n=i.needle.length-1;t<n;++t)e[i.needle[t]]=n-t;return function(t,n,r){let a=t.length,o=r+i.needleLength-1;for(;o<a;){for(let e=i.needleLength-1,r=o;e>=0&&t[r]===n[e];e--,r--)if(e===0)return r;o+=e[t[o]]}return-1}}let s=o();function c(e){let n=e.length;if(i.previousChunk!==void 0){let t=new Uint8Array(i.previousChunkLength+n);t.set(i.previousChunk),t.set(e,i.previousChunkLength),e=t,n=i.previousChunkLength+n,i.previousChunk=void 0}let r=0;for(;r<n;){let o=n-r;if(o<a){i.previousChunk=e.subarray(r),i.previousChunkLength=o;return}let c=s(e,i.needle,r);if(c>-1)c>r&&t(i.matchIndex,e.subarray(r,c)),i.matchIndex+=1,r=c+i.needleLength;else{if(e[n-1]in i.indexes){let a=i.indexes[e[n-1]],o=-1;for(let t=0,r=a.length;t<r;t++){let r=a[t];e[n-1-r]===i.firstByte&&t>o&&(o=r)}o===-1?r===0?t(i.matchIndex,e):t(i.matchIndex,e.subarray(r)):(n-1-o>r&&t(i.matchIndex,e.subarray(r,n-1-o)),i.previousChunk=e.subarray(n-1-o),i.previousChunkLength=o+1)}else r===0?t(i.matchIndex,e):t(i.matchIndex,e.subarray(r));break}}}function l(){i.previousChunk!==void 0&&i.previousChunk!==n&&t(i.matchIndex,i.previousChunk),i.previousChunk=n,i.previousChunkLength=n?.length??0,i.matchIndex=0}return{write:c,end:l}}const Jj={headers:0,body:1},Oce={_tag:`InvalidDisposition`},kce={_tag:`EndNotReached`},Ace={_tag:`ReachedLimit`,limit:`MaxParts`},jce={_tag:`ReachedLimit`,limit:`MaxTotalSize`},Mce={_tag:`ReachedLimit`,limit:`MaxPartSize`},Yj={_tag:`ReachedLimit`,limit:`MaxFieldSize`},Nce=/*#__PURE__*/ new TextEncoder().encode(`\r
|
|
23
|
+
`);function Xj(e){return e.filename!==void 0||e.contentType===`application/octet-stream`}function Pce(e){return Hj(e[`content-type`]).parameters.boundary}function Zj(e){}const Qj=e=>e===1/0?1/0:Number(oh(e));function Fce({headers:e,onFile:t,onField:n,onError:r,onDone:i,isFile:a=Xj,maxParts:o=1/0,maxTotalSize:s=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=Qj(s),d=Qj(c),f=Qj(l),p=Pce(e);if(p===void 0)return r({_tag:`InvalidBoundary`}),{write:Zj,end(){}};let m={state:Jj.headers,index:0,parts:0,onChunk:Zj,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0,done:!1,stopped:!1};function h(){m.state=Jj.body,m.isFile=!0,m.onChunk=Zj}function g(e){m.stopped=!0,m.state===Jj.body&&m.isFile&&m.onChunk(null),r(e)}let _=Tce(),v=Dce(`\r\n--${p}`,function(e,s){if(!m.stopped){if(e===0)h();else{if(e!==m.index){if(m.index>0){if(m.isFile)m.onChunk(null);else{if(m.fieldChunks.length===1)n(m.info,m.fieldChunks[0]);else{let e=new Uint8Array(m.fieldSize),t=0;for(let n=0;n<m.fieldChunks.length;n++){let r=m.fieldChunks[n];e.set(r,t),t+=r.length}n(m.info,e)}m.fieldSize=0,m.fieldChunks=[]}}if(m.partSize=0,m.state=Jj.headers,m.index=e,m.headerSkip=2,s[0]===45&&s[1]===45)return m.done=!0,i();if(m.parts++,m.parts>o)return g(Ace)}if((m.partSize+=s.length)>d)return g(Mce);if(m.state===Jj.headers){let e=_(s,m.headerSkip);if(m.headerSkip=0,e._tag===`Continue`)return;if(e._tag===`Failure`)return h(),r({_tag:`BadHeaders`,error:e});let n=Hj(e.headers[`content-type`]),i=Hj(e.headers[`content-disposition`],!0);if(i.value===`form-data`&&!(`name`in i.parameters))return h(),r(Oce);let o;if(`filename*`in i.parameters){let e=i.parameters[`filename*`].split(`''`);if(e.length===2)try{o=decodeURIComponent(e[1])}catch{o=e[1]}}if(m.info={name:i.parameters.name??``,filename:o??i.parameters.filename,contentType:n.value===``?i.parameters.filename===void 0?`text/plain`:`application/octet-stream`:n.value,contentTypeParameters:n.parameters,contentDisposition:i.value,contentDispositionParameters:i.parameters,headers:e.headers},m.state=Jj.body,m.isFile=a(m.info),m.isFile&&(m.onChunk=t(m.info)),e.endPosition<s.length){if(m.isFile)m.onChunk(s.subarray(e.endPosition));else{let t=s.subarray(e.endPosition);if((m.fieldSize+=t.length)>f)return g(Yj);m.fieldChunks.push(t)}}}else if(m.isFile)m.onChunk(s);else{if((m.fieldSize+=s.length)>f)return g(Yj);m.fieldChunks.push(s)}}}},Nce,2);return{write(e){if(!m.stopped)return(m.totalSize+=e.length)>u?g(jce):v.write(e)},end(){v.end(),!m.done&&!m.stopped&&g(kce),m.state=Jj.headers,m.index=0,m.parts=0,m.onChunk=Zj,m.info=void 0,m.totalSize=0,m.partSize=0,m.fieldChunks=[],m.fieldSize=0,m.done=!1,m.stopped=!1}}}const $j=/*#__PURE__*/ new TextDecoder(`utf-8`);function Ice(e){if(e===`utf-8`||e===`utf8`||e===``)return $j;try{return new TextDecoder(e)}catch{return $j}}function Lce(e,t){return Ice(e.contentTypeParameters.charset??`utf-8`).decode(t)}const Rce=Fce,zce=Xj,Bce=Lce,eM=`~effect/http/Multipart`,tM=`~effect/http/Multipart/MultipartError`,Vce=e=>Wce(e)?e:nM.fromReason(`InternalError`,e);var Hce=class extends zo{};const Uce={FileTooLarge:413,FieldTooLarge:413,BodyTooLarge:413,TooManyParts:413,InternalError:500,Parse:400};var nM=class e extends (/*#__PURE__*/ Bo(`MultipartError`)){static fromReason(t,n){return new e({reason:new Hce({_tag:t,cause:n})})}[tM]=tM;[aO]=!0;[Oj](){return F(aj({status:Uce[this.reason._tag]}))}get message(){return this.reason._tag}};const Wce=e=>N(e,tM),Gce=e=>ap(t=>{let n=da(t.context,sM);return F({headers:e,maxParts:t.getRef(iM),maxFieldSize:t.getRef(aM),maxPartSize:t.getRef(oM),maxTotalSize:t.getRef(DA),isFile:n.length===0?void 0:e=>!n.some(t=>e.contentType.includes(t))&&zce(e)})});var Kce=class extends tr{[eM];constructor(){super(),this[eM]=eM}};const qce=(e,t)=>B($E,n=>vp(GE(t.content,n.sink(e)),Vce)),Jce=/*#__PURE__*/ new TextEncoder,Yce=e=>{let t=Array.from(e),n=``,r=0;for(let e=t.length-1;e>=0&&(r+=Jce.encode(t[e]).length,!(r>128));e--)n=t[e]+n;return n===``||n===`.`||n===`..`?`file`:n},Xce=(e,t=qce)=>R(function*(){let n=yield*$E,r=yield*iD,i=yield*n.makeTempDirectoryScoped(),a=Object.create(null),o=/* @__PURE__ */ new Set,s=0;return yield*qE(e,e=>{if(e._tag===`Field`)return e.key in a?typeof a[e.key]==`string`?a[e.key]=[a[e.key],e.value]:a[e.key].push(e.value):a[e.key]=e.value,L;if(e.name===``)return L;let n=e,c=Yce(r.basename(n.name)),l=r.join(i,c);for(;o.has(l);)l=r.join(i,`${s++}-${c}`);o.add(l);let u=new Zce(n.key,n.name,n.contentType,l);return Array.isArray(a[e.key])?a[e.key].push(u):a[e.key]=[u],t(l,n)}),a}).pipe(mp(`PlatformError`,e=>z(nM.fromReason(`InternalError`,e))));var Zce=class extends Kce{_tag=`PersistedFile`;key;name;contentType;path;constructor(e,t,n,r){super(),this.key=e,this.name=t,this.contentType=n,this.path=r}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`PersistedFile`,key:this.key,name:this.name,contentType:this.contentType,path:this.path}}};const rM=e=>{let t=/* @__PURE__ */ new Map;return e.maxParts!==void 0&&t.set(iM.key,e.maxParts),e.maxFieldSize!==void 0&&t.set(aM.key,oh(e.maxFieldSize)),e.maxFileSize!==void 0&&t.set(oM.key,oh(e.maxFileSize)),e.maxTotalSize!==void 0&&t.set(DA.key,oh(e.maxTotalSize)),e.fieldMimeTypes!==void 0&&t.set(sM.key,e.fieldMimeTypes),ta(t)},iM=/*#__PURE__*/ _a(`effect/http/Multipart/MaxParts`,{defaultValue:()=>void 0}),aM=/*#__PURE__*/ _a(`effect/http/Multipart/MaxFieldSize`,{defaultValue:/*#__PURE__*/ Pt(/*#__PURE__*/ lh(10))}),oM=/*#__PURE__*/ _a(`effect/http/Multipart/MaxFileSize`,{defaultValue:()=>void 0}),sM=/*#__PURE__*/ _a(`effect/http/Multipart/FieldMimeTypes`,{defaultValue:/*#__PURE__*/ Pt([`application/json`])}),cM=`~effect/http/HttpServerRequest`,lM=/*#__PURE__*/ P(`effect/http/HttpServerRequest`);var uM=class extends (/*#__PURE__*/ P()(`effect/http/ParsedSearchParams`)){};const Qce=(e,t)=>{let n=Cx(e);return B(lM,e=>n(e.cookies,t))},$ce=(e,t)=>{let n=Cx(e);return B(lM,e=>n(e.headers,t))},ele=(e,t)=>{let n=Cx(e);return B(uM,e=>n(e,t))},tle=e=>{let t=e.headers.host??`localhost`,n=e.headers[`x-forwarded-proto`]===`https`?`https`:`http`;try{return ji(new URL(e.url,`${n}://${t}`))}catch{return Ai()}},dM=/*#__PURE__*/ new WeakMap,nle=(e,t)=>{let n=dM.get(e.source),r=n?(e,r)=>B(n(e,r),n=>t(e,n)):t;dM.set(e.source,r)},rle=e=>e,ile=/*#__PURE__*/ new WeakSet,ale=e=>ap(t=>{let n=ua(t.context,lM);return ile.add(n.source),e}),ole=/*#__PURE__*/ _a(`effect/http/HttpMiddleware/TracerDisabledWhen`,{defaultValue:()=>It}),sle=/*#__PURE__*/ _a(`@effect/platform/HttpMiddleware/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),cle=/*#__PURE__*/ _a(`effect/http/HttpMiddleware/TracerHeaderFilter`,{defaultValue:()=>It}),fM=(e,t)=>!e.cache.tracerEnabled||e.getRef(ole)(t),pM=(e,t)=>{if(!(t.status>=500&&t.status<600))return Dd(t);let n=nr();rr(0);try{return kd(new jj({reason:new Nj({request:e,response:t})}))}finally{rr(n)}},mM=/*#__PURE__*/ rle(e=>ap(t=>{let n=ua(t.context,lM);if(fM(t,n))return e;let r=t.getRef(sle),i=vu(t,r(n),{parent:zi(_se(n.headers)),kind:`server`}),a=t.context;return t.setContext(oa(t.context,Xo,i)),bl(t,e=>{t.setContext(a);let r=t.getRef(Tf).currentTimeNanosUnsafe();if(Nd(e)&&(!i.sampled||t.getRef(rs)===is)){i.end(r,pM(n,e.value));return}let o=t.getRef(wg),s=t.getRef(cle),c,l;if(Pd(e)){let[t,r]=yce(e.cause);c=t,l=Ni(r)&&(c.status>=500||yd(r.value))?Od(r.value):pM(n,c)}else c=e.value,l=pM(n,c);if(i.sampled){i.attribute(`http.request.method`,n.method);let e=tle(n);Ni(e)&&MA(i,e.value,t.getRef(Yg)),n.headers[`user-agent`]!==void 0&&i.attribute(`user_agent.original`,n.headers[`user-agent`]),NA(i,`request`,n.headers,s,o),Ni(n.remoteAddress)&&i.attribute(`client.address`,n.remoteAddress.value),i.attribute(`http.response.status_code`,c.status),NA(i,`response`,c.headers,s,o)}i.end(r,l)}),e})),lle=(e,t,n)=>{let r=(e,n)=>{e.cause=n;let r=e.request;return Sm(Lj(n),([e,n])=>{let i=QS();cd(i,n);let a=dM.get(r.source),o=n.reasons.length===0?F(e):tp(n);return a===void 0?(r[hM]=!0,Sm(t(r,e),()=>o)):Sm(Sm(a(r,e),e=>(r[hM]=!0,t(r,e))),()=>o)})},i=(e,n)=>{let r=dM.get(e.source);return r===void 0?(e[hM]=!0,ym(t(e,n),e=>ij(e)?e:n)):Sm(r(e,n),r=>(e[hM]=!0,ym(t(e,r),e=>ij(e)?e:n)))},a=a=>{let o=a.request,s=Op(e,{onSuccess:e=>i(o,e),onFailure:e=>r(a,e)});return n===void 0?s:Op(mM(n(s)),{onFailure(e){return cd(QS(),e),hM in o?L:die(Lj(e),{onFailure(e){return t(o,aj({status:500}))},onSuccess([e]){return t(o,e)}})},onSuccess(e){return hM in o?L:t(o,e)}})},o=e=>mM(a(e)),s=(e,t,n)=>Wp(n,n=>{if(t.setContext(e.prev),!(gM in e.scope))return ef(e.scope,e.cause===void 0?n:Od(e.cause))},!0);class c{scope;prev;request;cause;constructor(e,t,n){this.scope=e,this.prev=t,this.request=n}[mr](e,t){let n=i(this.request,e);if(vc(n)&&n._tag===`Success`){if(t.setContext(this.prev),gM in this.scope)return n;let e=ef(this.scope,n);return e===void 0?n:B(e,()=>n)}return s(this,t,n)}[hr](e,t){return s(this,t,r(this,e))}}return ap(t=>{Il(t);let r=qd(),i=new c(r,t.context,ua(t.context,lM));t.setContext(oa(i.prev,Kd,r));let l=t.cache.tracer;return n===void 0&&(l===void 0||l===is||fM(t,i.request))?(t._stack.push(i),e):s(i,t,n===void 0?o(i):a(i))})},hM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/handled`),gM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/scopeEjected`),ule=e=>lM.use(t=>(_M(t,e),L)),_M=nle,dle=/*#__PURE__*/ j(2,(e,t)=>lM.use(n=>(_M(n,t),e))),vM=`~effect/http/HttpRouter`,yM=/*#__PURE__*/ P(`effect/http/HttpRouter`),fle=/*#__PURE__*/ R(function*(){let e=yield*hle,t=e.ignoreDuplicateSlashes??!0,n=QA(e),r=/* @__PURE__ */ new Set,i=e=>jp(r=>{let i=MM(r),a=e=>{for(let t=0;t<i.length;t++)e=i[t](e);return e};for(let r=0;r<e.length;r++){let o=i.length===0?e[r]:wM({...e[r],handler:a(e[r].handler)}),s={route:o,prefixSegments:Ni(o.prefix)?mle(o.prefix.value,t):void 0};o.method===`*`?o.path.endsWith(`/*`)?(n.all(o.path,s),n.all(o.path.slice(0,-2),s)):n.all(o.path,s):o.path.endsWith(`/*`)?(n.on(o.method,o.path,s),n.on(o.method,o.path.slice(0,-2),s)):n.on(o.method,o.path,s)}return L});return yM.of({[vM]:vM,prefixed(e){return e=EM(e),yM.of({...this,prefixed:t=>this.prefixed(DM(t,e)),addAll:t=>i(t.map(vle(e))),add:(t,n,r,a)=>i([wM({method:t,path:DM(n,e),handler:ij(r)?F(r):Gf(r)?r:B(lM,r),uninterruptible:a?.uninterruptible??!1,prefix:e})])})},addAll:i,add:(e,t,n,r)=>i([TM(e,t,n,r)]),addGlobalMiddleware:e=>I(()=>{r.add(e)}),asHttpEffect(){let e=ap(e=>{let r=e.context,i=ua(r,lM),a=n.find(i.method,i.url);if(a===void 0&&i.method===`HEAD`&&(a=n.find(`GET`,i.url)),a===void 0)return z(new jj({reason:new _ce({request:i})}));let{route:o,prefixSegments:s}=a.handler;if(s!==void 0&&(r=oa(r,lM,ple(i,s,t))),r=oa(r,uM,a.searchParams),r=oa(r,bM,{route:o,params:a.params}),e.getRef(rs)!==is){let e=ca(r,Xo);e!==void 0&&e._tag===`Span`&&e.sampled&&e.attribute(`http.route`,o.path)}if(e.setContext(r),!o.uninterruptible){let t=Ll(e);if(t!==void 0)return t}return o.handler});if(r.size===0)return e;for(let t of Ste(r))e=t(e);return e}})});function ple(e,t,n){let r=e.url,i=0;for(let e=t;e>0;e--){if(n)for(;r[i]===`/`;)i++;else r[i]===`/`&&i++;for(;i<r.length&&!`/?;#`.includes(r[i]);)i++}return e.modify({url:i<r.length?r.slice(i):`/`})}function mle(e,t){let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`/`?((!t||e[i-1]!==`/`)&&n++,r=!1):a===`:`?e[i+1]===`:`?i++:r=!0:a===`-`||a===`.`?r=!1:a===`(`&&r&&(i=YA(e,i),r=!1)}return n}const hle=/*#__PURE__*/ _a(`effect/http/HttpRouter/RouterConfig`,{defaultValue:()=>({})});var bM=class extends (/*#__PURE__*/ P()(`effect/http/HttpRouter/RouteContext`)){};const xM=e=>gf(B(yM,e)),SM=(e,t,n,r)=>xM(i=>i.add(e,t,n,r)),gle=/*#__PURE__*/ pf(yM)(fle),_le=e=>jp(t=>{let n=da(t,Kd),r=cf.forkOrCreate(t);return V(lf(wf(e,gle),r,n),e=>da(e,yM).asHttpEffect())}),CM=`~effect/http/HttpRouter/Route`,wM=e=>({...e,uninterruptible:e.uninterruptible??!1,prefix:typeof e.prefix==`string`?ji(e.prefix):e.prefix??Ai(),[CM]:CM}),TM=(e,t,n,r)=>wM({...r,method:e,path:t,handler:ij(n)?F(n):Gf(n)?n:B(lM,n),uninterruptible:r?.uninterruptible??!1}),EM=e=>e.endsWith(`/`)?e.slice(0,-1):e,DM=/*#__PURE__*/ j(2,(e,t)=>(t=EM(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),vle=/*#__PURE__*/ j(2,(e,t)=>wM({...e,path:DM(e.path,t),prefix:Pi(e.prefix,{onNone:()=>EM(t),onSome:e=>DM(e,t)})})),OM=function(){return arguments.length===0?kM:kM(arguments[0],arguments[1])},kM=(e,t)=>t?.global?gf(R(function*(){let t=yield*yM,n=Gf(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new ble(Gf(e)?hf(V(e,e=>ta(/* @__PURE__ */ new Map([[AM,e]])))):df(ta(/* @__PURE__ */ new Map([[AM,e]]))));let yle=0;const AM=`effect/http/HttpRouter/MiddlewareFn`;var ble=class e{"~effect/http/HttpRouter/Middleware"={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++yle}`;this.layer=hf(R({self:this},function*(){let e=yield*Ap(),t=[la(e,AM)];if(this.dependencies){let n=yield*cf,r=da(e,Kd),i=yield*lf(this.dependencies,n,r);t.push(...MM(i))}return ta(/* @__PURE__ */ new Map([[n,t]]))})).pipe(Cf(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?wf(this.dependencies,t.layer):t.layer)}};const jM=/*#__PURE__*/ new WeakMap,MM=e=>{let t=jM.get(e);if(t)return t;let n=Pa(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=/* @__PURE__ */ new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=ka(e).reverse()}return jM.set(e,t),t};(/*#__PURE__*/ OM(ale)).layer;var NM=class extends (/*#__PURE__*/ P()(`effect/workers/Transferable/Collector`)){};const PM=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return NM.of({addAllUnsafe:t,addAll:e=>I(()=>t(e)),readUnsafe:n,read:I(n),clearUnsafe:r,clear:I(r)})},FM=(e,t)=>e===void 0?t:`${e}.${t}`,IM=(e,t)=>({"rpc.system.name":`effect_rpc`,"rpc.method":e,...t}),LM=`~effect/rpc/RpcSchema/StreamSchema`;function RM(e){return N(e,LM)}function zM(e){return RM(e)?ji({success:e.success,error:e.error}):Ai()}const xle=/*#__PURE__*/ vx(pE);function Sle(e,t){return Ax(xle.ast,{[LM]:LM,success:e,error:t})}var Cle=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSchema/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ oa(Td,{name:`ClientAbort`,stack:Lt,parent:void 0}))};const BM=`~effect/rpc/Rpc`;var VM=class{id;annotations;constructor(e){this.id=e,this.annotations=ia()}annotate(e,t){return this.annotations=oa(this.annotations,e,t),this}};const wle={[BM]:BM,pipe(){return jt(this,arguments)},setSuccess(e){return HM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return HM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return HM({_tag:this._tag,payloadSchema:jx(e)?e:W(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return HM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},prefix(e){return HM({_tag:`${e}${this._tag}`,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},annotate(e,t){return HM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:oa(this.annotations,e,t)})},annotateMerge(e){return HM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:ha(this.annotations,e)})}},HM=e=>{function t(){}return Object.setPrototypeOf(t,wle),Object.assign(t,e),t.key=`effect/rpc/Rpc/${e._tag}`,t},J=(e,t)=>{let n=t?.success??Hx,r=t?.error??Lx,i=t?.defect??yS(),a;return a=t?.primaryKey?class extends VS(`effect/rpc/Rpc/${e}`)(t.payload){"~effect/PrimaryKey"(){return t.primaryKey(this)}}:jx(t?.payload)?t?.payload:t?.payload?W(t?.payload):Hx,HM({_tag:e,payloadSchema:a,successSchema:t?.stream?Sle(n,r):n,errorSchema:t?.stream?Lx:r,defectSchema:i,annotations:ia(),middlewares:/* @__PURE__ */ new Set})},UM=/*#__PURE__*/ new WeakMap,WM=e=>{if(UM.has(e))return UM.get(e);let t=e,n=/* @__PURE__ */ new Set([t.errorSchema]),r=zM(t.successSchema);Ni(r)&&n.add(r.value.error);for(let e of t.middlewares)n.add(e.error);let i=MS(Ni(r)?Hx:t.successSchema,K([...n]),t.defectSchema);return UM.set(e,i),i},GM=e=>`~effect/rpc/Rpc/Wrapper`in e,KM=e=>e,Tle={_tag:`Eof`},qM=e=>({_tag:`Defect`,defect:e}),Ele={_tag:`Pong`},JM=GS;let Dle;const YM=e=>(Dle??=new TextDecoder).decode(e);var XM=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSerialization`)){};const Ole=/*#__PURE__*/ XM.of({contentType:`application/json`,includesFraming:!1,codecFor:JM,makeUnsafe:()=>({decode:e=>{let t=JSON.parse(typeof e==`string`?e:YM(e));return Array.isArray(t)?t:[t]},encode:e=>JSON.stringify(e)})}),ZM=e=>XM.of({contentType:e?.contentType??`application/json`,includesFraming:!1,codecFor:JM,makeUnsafe:()=>{let e=/* @__PURE__ */ new Map;return{decode:t=>kle(JSON.parse(typeof t==`string`?t:YM(t)),e),encode:t=>{let n=Ale(t,e);return n&&JSON.stringify(n)}}}});function kle(e,t){if(Array.isArray(e)){let n={size:0,responses:/* @__PURE__ */ new Map},r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!on(a))continue;let o=QM(a);r.push(o),o._tag===`Request`&&!o.isNotification&&(n.size++,t.set(o.id,n))}return r}return on(e)?[QM(e)]:[]}function QM(e){if(Object.hasOwn(e,`method`)){let t=e;if(rn(t.id)&&Jt(t.method)&&t.method.startsWith(`@effect/rpc/`)){let e=t.method.slice(12),n=t.params?.requestId;return n===void 0?{_tag:e}:{_tag:e,requestId:n}}return{_tag:`Request`,id:t.id??``,tag:t.method,payload:t.params??null,headers:t.headers??[],...N(t,`id`)?{}:{isNotification:!0},...t.spanId?{traceId:t.traceId,spanId:t.spanId,sampled:t.sampled}:{}}}let t=e,n=Object.hasOwn(t,`error`);return n&&t.error&&t.error._tag===`Defect`?{_tag:`Defect`,defect:t.error.data}:Object.hasOwn(t,`chunk`)&&t.chunk===!0?{_tag:`Chunk`,requestId:t.id??``,values:t.result}:{_tag:`Exit`,requestId:t.id??``,exit:n&&t.error!=null?{_tag:`Failure`,cause:t.error._tag===`Cause`?t.error.data:[{_tag:`Fail`,error:t.error}]}:{_tag:`Success`,value:t.result}}}function $M(e,t){if(!(`requestId`in e))return eN(e);let n=t.get(e.requestId);return n?(t.delete(e.requestId),n.responses.set(e.requestId,e),n.size===n.responses.size?Array.from(n.responses.values(),eN):void 0):eN(e)}function Ale(e,t){if(Array.isArray(e)===!1)return $M(e,t);if(e.length===0)return;let n=[];for(let r=0;r<e.length;r++){let i=$M(e[r],t);i!==void 0&&n.push(i)}if(n.length===0)return;if(n.length===1)return n[0];let r=[];for(let e=0;e<n.length;e++){let t=n[e];Array.isArray(t)?r.push(...t):r.push(t)}return r}function eN(e){switch(e._tag){case`Request`:return{jsonrpc:`2.0`,method:e.tag,params:e.payload,...e.isNotification?{}:{id:e.id},...e.headers?.length>0?{headers:e.headers}:{},traceId:e.traceId,spanId:e.spanId,sampled:e.sampled};case`Ping`:case`Pong`:case`Interrupt`:case`Ack`:case`Eof`:return{jsonrpc:`2.0`,method:`@effect/rpc/${e._tag}`,params:`requestId`in e?{requestId:e.requestId}:void 0};case`Chunk`:return{jsonrpc:`2.0`,chunk:!0,id:e.requestId,result:e.values};case`Exit`:{if(e.exit._tag===`Success`)return{jsonrpc:`2.0`,id:e.requestId??void 0,result:e.exit.value};let t=e.exit.cause.find(e=>e._tag===`Fail`),n=t?._tag===`Fail`?t.error:void 0;return{jsonrpc:`2.0`,id:e.requestId??void 0,error:e.exit._tag===`Failure`?{_tag:`Cause`,code:n&&N(n,`code`)?Number(n.code):0,message:n&&N(n,`message`)?n.message:JSON.stringify(e.exit.cause),data:e.exit.cause}:void 0}}case`Defect`:return{jsonrpc:`2.0`,id:jle,error:{_tag:`Defect`,code:1,message:`A defect occurred`,data:e.defect}};case`ClientProtocolError`:return{}}}const jle=-32603,Mle=e=>uf(XM)(ZM(e)),Nle=()=>e=>Qf(()=>{let t=Dw(1),n=[],r=(...e)=>jp(t=>(n.push([e,t]),L));return V(e((...e)=>r(...e)),e=>({...e,run(e){return t.withPermits(1)(R(function*(){let t=r;for(let[t,r]of n)yield*Np(Qf(()=>e(...t)),r);return n=[],r=e,yield*Gp(ep,()=>(r=t,L))}))}}))}),Ple=e=>Qf(()=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=(e,t)=>jp(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),L});return V(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return R(function*(){t.add(e),r.set(e,i);let a=n.get(e);if(a){n.delete(e);for(let[e,t]of a)yield*Np(Qf(()=>i(e)),t)}return yield*Gp(ep,()=>(t.delete(e),r.delete(e),L))})}}))});let Fle=0;const tN=/*#__PURE__*/ H(function*(e,t){let n=t.spanPrefix,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Fle++),o=yield*Ap(),s=da(o,Kd),c=/* @__PURE__ */ new Map,l=!1;yield*Xd(s,ap(e=>(l=!0,u(jd(e.id)))));let u=H(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?ew(n.queue):QC(n.queue,e.cause):n.resume(e)}),d=e=>{let r=RM(e.successSchema),a=m(e);return(o,s)=>{let c=s?.headers?hg(s.headers):mg,l=s?.context??ia();if(!r){let r=t=>f(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):$p(FM(n,e._tag),{kind:`client`,attributes:IM(e._tag,t.spanAttributes)},r)}let u=p(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:DE(V(u,TE))}},f=(e,n,r,i,o,s,u)=>ap(d=>{if(l)return qp;let f=a(),p=n(e=>t.onFromClient({message:e,context:s,discard:u}),{_tag:`Request`,id:f,tag:e._tag,payload:i,...r?{traceId:r.traceId,spanId:r.spanId,sampled:r.sampled}:{},headers:yg(d.getRef(nN),o)});if(u)return p;let m;return Yp($f(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&d.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(d.id)},0)}};c.set(f,n),m=p.pipe(r?tm(r,{captureStackTrace:!1}):M,om(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),sp(ZS(m),h(f,Array.from(e),s))))}),p=H(function*(e,r,o,s,u,d){if(l)return yield*qp;let f=i?void 0:yield*hie(FM(n,e._tag),{kind:`client`,attributes:IM(e._tag,t.spanAttributes)}),p=QS(),m=a(),g=ua(p.context,Kd),_=yield*KC(u);return yield*Yd(g,e=>(rw(_),c.has(m)?(c.delete(m),h(m,Pd(e)?Array.from(ure(e.cause)):[],d)):L)),c.set(m,{_tag:`Queue`,rpc:e,queue:_,scope:g,context:d}),yield*r(e=>t.onFromClient({message:e,context:d,discard:!1}),{_tag:`Request`,id:m,tag:e._tag,payload:o,...f?{traceId:f.traceId,spanId:f.spanId,sampled:f.sampled}:{},headers:yg(p.getRef(nN),s)}).pipe(f?tm(f,{captureStackTrace:!1}):M,Up(e=>QC(_,e)),Jp,rm(g,{startImmediately:!0})),_}),m=e=>{let t=[];for(let n of e.middlewares.values()){let e=la(o,`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},h=(e,n,r)=>$f(i=>{let a=QS();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(oie(1e3),om(a.context)).addObserver(()=>{i(L)})}),g=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?L:XC(i.queue,e.values).pipe(r?B(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):M,hp(e=>QC(i.queue,e)))}case`Exit`:{let t=e.requestId,n=c.get(t);return n?(c.delete(t),n._tag===`Effect`?(n.resume(e.exit),L):e.exit._tag===`Success`?ew(n.queue):QC(n.queue,e.exit.cause)):L}case`Defect`:return u(Ad(e.defect));case`ClientEnd`:return L}},_;if(t.flatten){let t=/* @__PURE__ */ new Map;_=function(n,r,i){let a=t.get(n);return a||(a=d(e.requests.get(n)),t.set(n,a)),a(r,i)}}else _={},e.requests.forEach(e=>{or(_,e._tag,d(e))});return{client:_,write:g}});let Ile=0;const Lle=/*#__PURE__*/ H(function*(e,t){let n=Ile++,{codecFor:r,run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*rN,c=Rle(r),l=Aoe(r(yS())),u=/* @__PURE__ */ new Map,d=e=>u.has(e)?(u.delete(e),a(n,{_tag:`Interrupt`,requestId:e})):L,{client:f,write:p}=yield*tN(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),i=s?PM():void 0,o=QS(),l={rpc:r,context:i?oa(o.context,NM,i):o.context,schemas:c(r)};return u.set(t.id,l),l.schemas.encodePayload(t.payload).pipe(Np(l.context),yp,B(e=>a(n,{...t,id:t.id,payload:e,headers:Object.entries(t.headers)},i&&i.readUnsafe())))}case`Ack`:return u.get(t.requestId)?a(n,{_tag:`Ack`,requestId:t.requestId}):L;case`Interrupt`:return d(t.requestId);case`Eof`:return L}}});return yield*i(n,e=>{switch(e._tag){case`Chunk`:{let t=KM(e.requestId),n=u.get(t);if(!n||Mi(n.schemas.decodeChunk))return L;let r=n.schemas.decodeChunk.value;return Zp(i=>i(r(e.values).pipe(Np(n.context),yp,B(e=>p({_tag:`Chunk`,clientId:0,requestId:t,values:e})))).pipe(Up(e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Od(e)}).pipe(sp(yd(e)?L:Sp(d(t))))),iie(e=>!yd(e),()=>L)))}case`Exit`:{let t=KM(e.requestId),n=u.get(t);return n?(u.delete(t),n.schemas.decodeExit(e.exit).pipe(Np(n.context),yp,Op({onSuccess:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Od(e)})}))):L}case`Defect`:return p({_tag:`Defect`,clientId:0,defect:l(e.defect)});case`ClientProtocolError`:{let t=kd(e.error);return qf(Array.from(u.keys()),e=>p({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return L}}).pipe(hp(mm),Jp,im),f}),Rle=e=>{let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=zM(n.successSchema);return r={decodeChunk:Vi(i,t=>Cx(e(Jx(t.success)))),encodePayload:Dx(e(n.payloadSchema)),decodeExit:Cx(e(WM(n)))},t.set(n,r),r}},nN=/*#__PURE__*/ _a(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>mg});var rN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcClient/Protocol`)){static make=Ple};const zle=/*#__PURE__*/ H(function*(e,t){let n=t.disableTracing!==!0,r=t.disableSpanPropagation!==!0,i=t.disableClientAcks!==!0,a=t.spanPrefix,o=t.concurrency??`unbounded`,s=t.disableFatalDefects??!1,c=yield*Ap(),l=da(c,Kd),u=$S(Qd(l,`parallel`)),d=o===`unbounded`?void 0:yield*Aw(o),f=/* @__PURE__ */ new Map,p=!1,m=eC(!1);yield*Xd(l,ap(e=>{p=!0;for(let t of f.values())if(t.ended=!0,t.fibers.size===0)u(om(c)(_(t)));else for(let n of t.fibers.values())n.interruptUnsafe(e.id);return f.size===0?L:m.await}));let h=e=>ap(t=>{let n=f.get(e);if(!n)return L;for(let e of n.fibers.values())e.interruptUnsafe(t.id);return f.delete(e),L}),g=(e,n,r)=>gp(ap(i=>{if(p)return qp;let a=f.get(e);if(!a)a={id:e,latches:void 0,fibers:/* @__PURE__ */ new Map,ended:!1,serverClient:new VM(e)},f.set(e,a);else if(a.ended&&(n._tag!==`Interrupt`&&n._tag!==`Ack`||!a.fibers.has(n.requestId)))return qp;switch(n._tag){case`Request`:return v(i,a,n,r);case`Ack`:{let e=a.latches?.get(n.requestId);return e?fp(e.open):L}case`Interrupt`:{let r=a.fibers.get(n.requestId);return r?(r.interruptUnsafe(i.id,Cle.annotation),L):t.onFromServer({_tag:`Exit`,clientId:e,requestId:n.requestId,exit:jd()})}case`Eof`:return a.ended=!0,a.fibers.size>0?L:_(a);default:return b(a,`Unknown request tag: ${n._tag}`)}}),t=>b(f.get(e),t)),_=e=>{f.delete(e.id);let n=t.onFromServer({_tag:`ClientEnd`,clientId:e.id});return p&&f.size===0?sp(n,m.open):n},v=(i,o,l,f)=>{if(o.fibers.has(l.id))return qp;let p=e.requests.get(l.tag),m=la(c,p?.key);if(!p||!m){let e=gp(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Ad(`Unknown request tag: ${l.tag}`)}),e=>b(o,e));return!o.ended||o.fibers.size>0?e:Hp(e,_(o))}let h=RM(p.successSchema),g={rpc:p,client:o.serverClient,requestId:l.id,headers:l.headers,payload:l.payload},v=m.handler(l.payload,g),x=GM(v),S=x&&v.fork,ee=x&&v.uninterruptible,C=x?v.value:v,te,w=h?y(o,l,C,e=>{te=e}):C,ne=p.middlewares.size===0?w:h?B(up(lN(c,w,g)),e=>te?tp(te):e):lN(c,w,g),T=!1,re=qd(),ie,ae=Gp(ne,e=>{T=!0;let n;if(e._tag===`Success`)_re(e.value)?(ie=e.value,n=L):n=t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});else if(te)return ef(re,e)??L;else n=!s&&vd(e.cause)&&!yd(e.cause)?b(o,_d(e.cause)):t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});let r=ef(re,e);return e._tag===`Failure`&&cd(QS(),e.cause),r?Hp(n,r):n});if(f?.onRequest&&(ae=f.onRequest(ae)),n){let e=ca(i.context,Xo);ae=em(ae,FM(a,l.tag),{captureStackTrace:!1,kind:`server`,attributes:IM(l.tag,t.spanAttributes),parent:r&&l.spanId?Qo({traceId:l.traceId,spanId:l.spanId,sampled:l.sampled}):void 0,links:r&&e?[{span:e,attributes:{}}]:void 0})}!S&&d&&(ae=d.withPermit(ae));let oe=om(oa(Hle(m,i.context),Kd,re));return u(oe(ap(e=>(o.fibers.set(l.id,e),ae)),ee?{uninterruptible:!0}:void 0)).addObserver(function e(n){if(ie){let n=u(oe(Gp(zd(ie),e=>t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e}))));o.fibers.set(l.id,n),ie=void 0,n.addObserver(e)}else!T&&n._tag===`Failure`&&u(oe(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:jd()}))),o.fibers.delete(l.id),o.latches?.delete(l.id),o.ended&&o.fibers.size===0&&u(oe(_(o)))}),L},y=(e,n,r,a)=>{let o=r=>Up(t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r}),e=>(sre(e)||a(e),L)),s;return i&&(e.latches??=/* @__PURE__ */ new Map,s=e.latches.get(n.id),s||(s=eC(!1),e.latches.set(n.id,s))),Gf(r)?r.pipe(B(e=>Jf({while:Ft,body:Pt(B(iw(e),e=>{let t=o(e);return s?(s.closeUnsafe(),B(t,()=>s.await)):t})),step:Rt})),If(()=>L),zp):JE(r,e=>{let t=o(e);return s?(s.closeUnsafe(),sp(t,s.await)):t})},b=(e,n)=>Qf(()=>{let r=e.ended&&e.fibers.size===0,i=t.onFromServer({_tag:`Defect`,clientId:e.id,defect:n});return r?sp(i,_(e)):i});return M({write:g,disconnect:h})}),iN=e=>e===Ole.codecFor,aN=/*#__PURE__*/ new WeakMap,Ble=(e,t)=>{let n=iN(e),r=n?aN.get(t):void 0;if(r===void 0){let i=zM(t.successSchema);r={decode:Cx(e(t.payloadSchema)),encodeChunk:Ex(e(Jx(Ni(i)?i.value.success:Rx))),encodeExit:Ex(e(WM(t)))},n&&aN.set(t,r)}return r};let Vle;const oN=e=>({encodeDefectUnsafe:kx(e(yS())),encodeUnknownRequestExit:Ex(e(MS(Lx,Lx,yS())))}),sN=e=>iN(e)?Vle??=oN(e):oN(e),cN=/*#__PURE__*/ new WeakMap,Hle=(e,t)=>{let n=cN.get(e);n===void 0&&(n=/* @__PURE__ */ new WeakMap,cN.set(e,n));let r=n.get(t);return r===void 0&&(r=ha(e.context,t),n.set(t,r)),r},lN=(e,t,n)=>{for(let r of n.rpc.middlewares)t=ua(e,r)(t,n);return t},Ule=/*#__PURE__*/ H(function*(e,t){let{codecFor:n,disconnects:r,end:i,run:a,send:o,supportsAck:s,supportsSpanPropagation:c,supportsTransferables:l}=yield*uN,{encodeDefectUnsafe:u,encodeUnknownRequestExit:d}=sN(n),f=yield*Ap(),p=yield*Cre(),m=yield*zle(e,{...t,disableClientAcks:!s,disableSpanPropagation:!c,onFromServer(e){let t=_.get(e.clientId);if(!t)return L;switch(e._tag){case`Chunk`:{let n=t.schemas.get(e.requestId);return n?y(t,e.requestId,n,n.encodeChunk(e.values),`Chunk`):L}case`Exit`:{let n=t.schemas.get(e.requestId);return n?(t.schemas.delete(e.requestId),y(t,e.requestId,n,n.encodeExit(e.exit),`Exit`)):L}case`Defect`:return x(t,e.defect);case`ClientEnd`:return _.delete(e.clientId),i(e.clientId)}}}).pipe(Jd(p));yield*nm(Jf({while:Ft,body:Pt(B(sw(r),e=>(_.delete(e),m.disconnect(e)))),step:Rt}));let h=/* @__PURE__ */ new WeakMap,g=e=>{let t=h.get(e);if(!t){let r=la(f,e.key);t={tag:e._tag,...Ble(n,e),context:r.context},h.set(e,t)}return t},_=/* @__PURE__ */ new Map,v=(e,t,n)=>t===`Chunk`?{_tag:`Chunk`,requestId:e,values:n}:{_tag:`Exit`,requestId:e,exit:n},y=(e,t,n,r,i)=>{let a=n.collector,s=!1,c=Ed(r)&&Nd(r)?o(e.id,v(t,i,r.value),a&&a.clearUnsafe()):B(pp(Np(a?Lp(r,NM,a):r,n.context),e=>ap(t=>{let r=pd(`Failed to encode response for RPC "${n.tag}": ${H_(e.issue)}`);return cd(t,r),s=!0,tp(r)})),n=>o(e.id,v(t,i,n),a&&a.clearUnsafe()));return hp(c,r=>(e.schemas.delete(t),sp(b(e,t,n.encodeExit,_d(r)),s?tp(r):m.write(e.id,{_tag:`Interrupt`,requestId:t,interruptors:[]}))))},b=(e,t,n,r)=>hp(B(n(Ad(r)),n=>o(e.id,v(t,`Exit`,n))),t=>x(e,_d(t))),x=(e,t)=>hp(o(e.id,qM(u(t))),e=>_m(gm(e),{module:`RpcServer`,method:`sendDefect`})),S=(e,t,n,r,i)=>{e.schemas.set(t,l?{...n,collector:PM()}:n);let a=r;return a.id=t,a.payload=i,a.headers=hg(r.headers),m.write(e.id,a)};return yield*a((t,n)=>{let r=_.get(t);switch(r||(r={id:t,schemas:/* @__PURE__ */ new Map},_.set(t,r)),n._tag){case`Request`:{let t=Object.hasOwn(n,`tag`)?n.tag:``,i;switch(typeof n.id){case`number`:case`string`:i=KM(n.id);break;default:return x(r,`Invalid request id: ${n.id}`)}let a=e.requests.get(t);if(!a)return b(r,i,d,`Unknown request tag: ${t}`);let o=g(a),s=o.decode(n.payload);return Ed(s)&&Nd(s)?S(r,i,o,n,s.value):kp(Np(s,o.context),{onFailure:e=>b(r,i,o.encodeExit,H_(e.issue)),onSuccess:e=>S(r,i,o,n,e)})}case`Ping`:return hp(o(r.id,Ele),e=>x(r,_d(e)));case`Eof`:return m.write(t,n);case`Ack`:return m.write(t,n);case`Interrupt`:return m.write(t,{...n,requestId:KM(n.requestId),interruptors:[]});default:return x(r,`Unknown request tag: ${n._tag}`)}}).pipe(xp(e=>fm(`BUG: RpcServer protocol crashed`,e)),Gp(e=>$d(p,e)))});var uN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcServer/Protocol`)){static make=/*#__PURE__*/ Nle()};const dN=/*#__PURE__*/ H(function*(e={}){let t=yield*XM,{encodeDefectUnsafe:n}=sN(t.codecFor),r=t.includesFraming,i=!t.contentType.includes(`json`),a=yield*GC(),o,s=0,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=new TextEncoder,d=R(function*(){let d=QS(),f=ua(d.context,lM),p=ua(d.context,Kd),m=Object.entries(f.headers),h=yield*yp(i?V(f.arrayBuffer,e=>new Uint8Array(e)):f.text),g=s++,_=yield*GC({capacity:r&&e.streamBufferSize!==`unbounded`?e.streamBufferSize??16:void 0}),v=t.makeUnsafe(),y=[],b=e=>typeof e==`string`?JC(_,u.encode(e)):JC(_,e),x={write:r?e=>{try{let t=v.encode(e);return t===void 0?L:b(t)}catch(e){return b(v.encode(qM(n(e))))}}:e=>e._tag===`Request`&&e.isNotification===!0?L:JC(_,e),end:ew(_)};yield*Yd(p,()=>(c.delete(g),l.delete(g),YC(a,g),_.state._tag===`Done`?L:sp(nw(_),qf(y,e=>o(g,{_tag:`Interrupt`,requestId:e}),{discard:!0})))),c.set(g,x),l.add(g);try{let e=v.decode(h);for(let t=0;t<e.length;t++){let n=e[t];n._tag===`Request`&&(y.push(KM(n.id)),n.headers=m.concat(n.headers)),yield*o(g,n)}}catch(e){yield*x.write(qM(n(e)))}if(yield*o(g,Tle),!r){let e=yield*aw(_),n=v.encode(e);return lj(n===void 0?``:n,{contentType:t.contentType})}let S=yield*If(iw(_),()=>F([]));return _.state._tag===`Done`?sj(Wle(S),{contentType:t.contentType}):fj(wE(S).pipe(AE(TE(_))),{contentType:t.contentType})});return{protocol:yield*uN.make(e=>(o=e,F({disconnects:a,send(e,t){let n=c.get(e);return n?n.write(t):L},end(e){let t=c.get(e);return t?t.end:L},clientIds:I(()=>l),initialMessage:Zf,supportsAck:!1,supportsTransferables:!1,supportsSpanPropagation:!1,supportsNotifications:r,codecFor:t.codecFor}))),httpEffect:d}}),Wle=e=>{if(e.length===0)return/* @__PURE__ */ new Uint8Array;if(e.length===1)return e[0];let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n},Gle={add(...e){let t=new Map(this.requests);for(let n of e)t.set(n._tag,n);return fN({requests:t,annotations:this.annotations})},merge(...e){let t=new Map(this.requests),n=new Map(this.annotations.mapUnsafe);for(let r of e){for(let[e,n]of r.requests)t.set(e,n);for(let[e,t]of r.annotations.mapUnsafe)n.set(e,t)}return fN({requests:t,annotations:ta(n)})},omit(...e){let t=new Map(this.requests);for(let n of e)t.delete(n);return fN({requests:t,annotations:this.annotations})},middleware(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.middleware(e));return fN({requests:t,annotations:this.annotations})},toHandlers(e){let t=this;return R(function*(){let n=yield*Ap(),r=Gf(e)?yield*e:e,i=/* @__PURE__ */ new Map;return t.requests.forEach((e,t)=>{i.set(e.key,{tag:e._tag,handler:r[t],context:n})}),ta(i)})},prefix(e){let t=/* @__PURE__ */ new Map;for(let n of this.requests.values()){let r=n.prefix(e);t.set(r._tag,r)}return fN({requests:t,annotations:this.annotations})},toLayer(e){return hf(this.toHandlers(e))},of:M,toLayerHandler(e,t){let n=this;return hf(R(function*(){let r=yield*Ap(),i=Gf(t)?yield*t:t,a=/* @__PURE__ */ new Map,o=n.requests.get(e);return a.set(o.key,{handler:i,context:r}),ta(a)}))},accessHandler(e){return jp(t=>{let n=this.requests.get(e),{handler:r,context:i}=la(t,n.key);return F((e,t)=>{t.rpc=n;let a=r(e,t),o=GM(a)?a.value:a;return Gf(o)?Mp(o,i):WE(o,i)})})},annotate(e,t){return fN({requests:this.requests,annotations:oa(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsMerge(aa(e,t))},annotateMerge(e){return fN({requests:this.requests,annotations:ha(this.annotations,e)})},annotateRpcsMerge(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.annotateMerge(ha(e,r.annotations)));return fN({requests:t,annotations:this.annotations})}},fN=e=>Object.assign(function(){},Gle,{requests:e.requests,annotations:e.annotations}),pN=(...e)=>fN({requests:new Map(e.map(e=>[e._tag,e])),annotations:ia()}),Kle=e=>{switch(e){case`SHA-1`:return`sha1`;case`SHA-256`:return`sha256`;case`SHA-384`:return`sha384`;case`SHA-512`:return`sha512`}},qle=/* @__PURE__ */ uf(tO,/* @__PURE__ */ nO({randomBytes:st.randomBytes,digest:(e,t)=>ip({try:()=>Uint8Array.from(st.createHash(Kle(e)).update(t).digest()),catch:e=>MT({module:`Crypto`,method:`digest`,_tag:`Unknown`,description:`Could not compute digest`,cause:e})})})),mN=e=>t=>NT({module:`FileSystem`,method:e,description:t.message??String(t)}),hN=(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n))throw RangeError(`${t} exceeds the safe integer range: ${e}`);return n},gN=e=>Hi(Li(e),Wm),_N=e=>BigInt.asUintN(64,e),vN=e=>Vi(Li(e),_N),yN=(e,t)=>ip({try:()=>hN(e,`position`),catch:mN(t)}),Jle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.access,/*#__PURE__*/ vk(`FileSystem`,`access`),/*#__PURE__*/ mN(`access`));return(t,n)=>{let r=Et.constants.F_OK;return n?.readable&&(r|=Et.constants.R_OK),n?.writable&&(r|=Et.constants.W_OK),e(t,r)}})(),Yle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.cp,/*#__PURE__*/ vk(`FileSystem`,`copy`),/*#__PURE__*/ mN(`copy`));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),Xle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.copyFile,/*#__PURE__*/ vk(`FileSystem`,`copyFile`),/*#__PURE__*/ mN(`copyFile`));return(t,n)=>e(t,n)})(),Zle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.chmod,/*#__PURE__*/ vk(`FileSystem`,`chmod`),/*#__PURE__*/ mN(`chmod`));return(t,n)=>e(t,n)})(),Qle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.chown,/*#__PURE__*/ vk(`FileSystem`,`chown`),/*#__PURE__*/ mN(`chown`));return(t,n,r)=>e(t,n,r)})(),$le=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.glob,/*#__PURE__*/ vk(`FileSystem`,`glob`),/*#__PURE__*/ mN(`glob`));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),eue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.link,/*#__PURE__*/ vk(`FileSystem`,`link`),/*#__PURE__*/ mN(`link`));return(t,n)=>e(t,n)})(),tue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.mkdir,/*#__PURE__*/ vk(`FileSystem`,`makeDirectory`),/*#__PURE__*/ mN(`makeDirectory`));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),bN=e=>{let t=vm(Et.mkdtemp,vk(`FileSystem`,e),mN(e));return e=>Qf(()=>{let n=e?.prefix??``,r=typeof e?.directory==`string`?ut.join(e.directory,`.`):vt.tmpdir();return t(n?ut.join(r,n):r+`/`)})},nue=/*#__PURE__*/ bN(`makeTempDirectory`),xN=e=>{let t=vm(Et.rm,vk(`FileSystem`,e),mN(e));return(e,n)=>t(e,{recursive:n?.recursive??!1,force:n?.force??!1})},rue=/*#__PURE__*/ xN(`remove`),iue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ bN(`makeTempDirectoryScoped`),t=/*#__PURE__*/ xN(`makeTempDirectoryScoped`);return n=>Bp(e(n),e=>yp(t(e,{recursive:!0})))})(),aue=e=>{let{O_APPEND:t,O_CREAT:n,O_EXCL:r,O_RDONLY:i,O_RDWR:a,O_TRUNC:o,O_WRONLY:s}=Et.constants;switch(e){case`r`:return i;case`r+`:return a;case`w`:return o|n|s;case`wx`:return o|n|s|r;case`w+`:return o|n|a;case`wx+`:return o|n|a|r;case`a`:return t|n|s;case`ax`:return t|n|s|r;case`a+`:return t|n|a;case`ax+`:return t|n|a|r}},oue=(e,t)=>Qf(()=>{let{O_NOFOLLOW:n}=Et.constants;return process.platform===`win32`||typeof n!=`number`||n===0?z(NT({module:`FileSystem`,method:e,description:`noFollow is not supported on this platform`})):F(aue(t)|n)}),sue=/*#__PURE__*/ (e=>{let t=vm(Et.open,vk(`FileSystem`,e),mN(e)),n=vm(Et.close,vk(`FileSystem`,e),mN(e));return(r,i)=>zt(Bp(i?.noFollow===!0?B(oue(e,i.flag??`r`),e=>t(r,e,i.mode)):t(r,i?.flag??`r`,i?.mode),e=>yp(n(e))),V(e=>cue(e,i?.flag?.startsWith(`a`)??!1)))})(`open`),SN=e=>NT({module:`FileSystem`,method:e,description:`Cannot read before the start of the file`}),cue=/*#__PURE__*/ (()=>{let e=e=>vm(Et.read,vk(`FileSystem`,e),mN(e)),t=/*#__PURE__*/ e(`read`),n=/*#__PURE__*/ e(`readAlloc`),r=/*#__PURE__*/ vm(Et.fstat,/*#__PURE__*/ vk(`FileSystem`,`stat`),/*#__PURE__*/ mN(`stat`)),i=/*#__PURE__*/ vm(Et.ftruncate,/*#__PURE__*/ vk(`FileSystem`,`truncate`),/*#__PURE__*/ mN(`truncate`)),a=/*#__PURE__*/ vm(Et.fsync,/*#__PURE__*/ vk(`FileSystem`,`sync`),/*#__PURE__*/ mN(`sync`)),o=e=>vm(Et.write,vk(`FileSystem`,e),mN(e)),s=/*#__PURE__*/ o(`write`),c=/*#__PURE__*/ o(`writeAll`);class l{[tD];fd;append;position=/*#__PURE__*/ BigInt(0);constructor(e,t){this[tD]=tD,this.fd=e,this.append=t}get stat(){return B(r(this.fd,{bigint:!0}),wN)}get sync(){return a(this.fd)}seek(e,t){return Qf(()=>{let n=t===`start`?e:this.position+e;return n<BigInt(0)?z(NT({module:`FileSystem`,method:`seek`,description:`Cannot seek before the start of the file`})):(this.position=n,F(n))})}read(e,n){return Qf(()=>{let r=n?.position;if(r!==void 0)return r<BigInt(0)?z(SN(`read`)):t(this.fd,{buffer:e,position:r});let i=this.position;return V(t(this.fd,{buffer:e,position:i}),e=>(this.position=i+BigInt(e),e))})}readAlloc(e,t){return Qf(()=>{try{if(!Number.isInteger(e)||e<0)throw RangeError(`size must be a non-negative integer`);let r=t?.position;if(r!==void 0&&r<BigInt(0))return z(SN(`readAlloc`));let i=Buffer.allocUnsafeSlow(e),a=r??this.position;return V(n(this.fd,{buffer:i,position:a}),t=>{if(t===0)return Ai();if(r===void 0&&(this.position=a+BigInt(t)),t===e)return ji(i);let n=Buffer.allocUnsafeSlow(t);return i.copy(n,0,0,t),ji(n)})}catch(e){return z(mN(`readAlloc`)(e))}})}truncate(e){return V(i(this.fd,e||void 0),()=>{if(!this.append){let t=BigInt(e??0);this.position>t&&(this.position=t)}})}write(e){return Qf(()=>{let t=this.position;return B(this.append?F(void 0):yN(t,`write`),n=>V(s(this.fd,e,void 0,void 0,n),e=>(this.append||(this.position=t+BigInt(e)),e)))})}writeAllChunk(e){return Qf(()=>{let t=this.position;return B(this.append?F(void 0):yN(t,`writeAll`),n=>B(c(this.fd,e,void 0,void 0,n),n=>n===0?z(MT({module:`FileSystem`,method:`writeAll`,_tag:`WriteZero`,pathOrDescriptor:this.fd,description:`write returned 0 bytes written`})):(this.append||(this.position=t+BigInt(n)),n<e.length?this.writeAllChunk(e.subarray(n)):L)))})}writeAll(e){return e.length===0?L:this.writeAllChunk(e)}}return(e,t)=>new l(e,t)})(),CN=e=>{let t=bN(e);return H(function*(e){let n=yield*t(e),r=st.randomBytes(6).toString(`hex`),i=ut.join(n,e?.suffix?`${r}${e.suffix}`:r);return yield*EN(i,/* @__PURE__ */ new Uint8Array),i})},lue=/*#__PURE__*/ CN(`makeTempFile`),uue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ CN(`makeTempFileScoped`),t=/*#__PURE__*/ xN(`makeTempFileScoped`);return n=>Bp(e(n),e=>yp(t(ut.dirname(e),{recursive:!0})))})(),due=(e,t)=>Xf({try:()=>Et.promises.readdir(e,t),catch:t=>vk(`FileSystem`,`readDirectory`)(t,[e])}),fue=e=>$f((t,n)=>{try{Et.readFile(e,{signal:n},(n,r)=>{t(n?z(vk(`FileSystem`,`readFile`)(n,[e])):F(r))})}catch(e){t(z(mN(`readFile`)(e)))}}),pue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.readlink,/*#__PURE__*/ vk(`FileSystem`,`readLink`),/*#__PURE__*/ mN(`readLink`));return t=>e(t)})(),mue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.realpath,/*#__PURE__*/ vk(`FileSystem`,`realPath`),/*#__PURE__*/ mN(`realPath`));return t=>e(t)})(),hue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.rename,/*#__PURE__*/ vk(`FileSystem`,`rename`),/*#__PURE__*/ mN(`rename`));return(t,n)=>e(t,n)})(),wN=e=>ip({try:()=>({type:e.isFile()?`File`:e.isDirectory()?`Directory`:e.isSymbolicLink()?`SymbolicLink`:e.isBlockDevice()?`BlockDevice`:e.isCharacterDevice()?`CharacterDevice`:e.isFIFO()?`FIFO`:e.isSocket()?`Socket`:`Unknown`,mtime:Li(e.mtime),atime:Li(e.atime),birthtime:Li(e.birthtime),dev:_N(e.dev),rdev:vN(e.rdev),ino:vN(e.ino),mode:hN(e.mode,`mode`),nlink:vN(e.nlink),uid:gN(e.uid),gid:gN(e.gid),size:ch(e.size),blksize:e.blksize===void 0?Ai():ji(ch(e.blksize)),blocks:Li(e.blocks)}),catch:mN(`stat`)}),TN=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.stat,/*#__PURE__*/ vk(`FileSystem`,`stat`),/*#__PURE__*/ mN(`stat`));return t=>B(e(t,{bigint:!0}),wN)})(),gue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.symlink,/*#__PURE__*/ vk(`FileSystem`,`symlink`),/*#__PURE__*/ mN(`symlink`));return(t,n)=>e(t,n)})(),_ue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.truncate,/*#__PURE__*/ vk(`FileSystem`,`truncate`),/*#__PURE__*/ mN(`truncate`));return(t,n)=>e(t,n)})(),vue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ vm(Et.utimes,/*#__PURE__*/ vk(`FileSystem`,`utime`),/*#__PURE__*/ mN(`utime`));return(t,n,r)=>e(t,n,r)})(),yue=(e,t,n)=>bE(r=>Bp(I(()=>{let i=t.type===`Directory`?e:ut.dirname(e),a=Et.watch(e,{recursive:n?.recursive??!1},(e,t)=>{if(t)switch(e){case`rename`:am(kp(TN(ut.resolve(i,t)),{onSuccess:e=>JC(r,{_tag:`Create`,path:t}),onFailure:e=>JC(r,{_tag:`Remove`,path:t})}));return;case`change`:YC(r,{_tag:`Update`,path:t});return}});return a.on(`error`,t=>{$C(r,are(MT({module:`FileSystem`,_tag:`Unknown`,method:`watch`,pathOrDescriptor:e,cause:t})))}),a.on(`close`,()=>{tw(r)}),a}),e=>I(()=>e.close())).pipe(cp(()=>I(()=>n?.onReady?.())))),bue=(e,t,n)=>Kf([TN(t),Fp(nD)]).pipe(V(([r,i])=>Ii(i,()=>e).pipe(Hi(e=>e.register(t,r,n)),Fi(()=>yue(t,r,n)))),DE),EN=(e,t,n)=>$f((r,i)=>{try{Et.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},t=>{r(t?z(vk(`FileSystem`,`writeFile`)(t,[e])):L)})}catch(e){r(z(mN(`writeFile`)(e)))}}),xue=/*#__PURE__*/ V(/*#__PURE__*/ Fp(nD),e=>eD({access:Jle,chmod:Zle,chown:Qle,copy:Yle,copyFile:Xle,glob:$le,link:eue,makeDirectory:tue,makeTempDirectory:nue,makeTempDirectoryScoped:iue,makeTempFile:lue,makeTempFileScoped:uue,open:sue,readDirectory:due,readFile:fue,readLink:pue,realPath:mue,remove:rue,rename:hue,stat:TN,symlink:gue,truncate:_ue,utimes:vue,watch(t,n){return bue(e,t,n)},writeFile:EN})),DN=/* @__PURE__ */ pf($E)(xue),ON=/*#__PURE__*/ new TextDecoder;var Sue=class extends tr{[TA];source;onError;remoteAddressOverride;constructor(e,t,n){super(),this[TA]=TA,this.source=e,this.onError=t,this.remoteAddressOverride=n}get headers(){return hg(this.source.headers)}get remoteAddress(){return this.remoteAddressOverride??Li(this.source.socket?.remoteAddress)}textEffect;get text(){return this.textEffect||=V(this.arrayBuffer,e=>ON.decode(e)),this.textEffect}get textUnsafe(){return cm(this.text)}get json(){return B(this.text,e=>ip({try:()=>e===``?null:JSON.parse(e),catch:this.onError}))}get jsonUnsafe(){return cm(this.json)}get urlParamsBody(){return B(this.text,e=>ip({try:()=>Ag(new URLSearchParams(e)),catch:this.onError}))}get stream(){return Sk({evaluate:()=>this.source,onError:this.onError})}arrayBufferEffect;get arrayBuffer(){return this.arrayBufferEffect||(this.arrayBufferEffect=ap(e=>Ek(()=>this.source,{onError:this.onError,maxBytes:e.getRef(DA)})).pipe(Kp,cm),this.textEffect=V(this.arrayBufferEffect,e=>ON.decode(e))),this.arrayBufferEffect}};const kN=/*#__PURE__*/ _a(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch});var AN=class extends (/*#__PURE__*/ P()(`effect/http/FetchHttpClient/RequestInit`)){};const jN=/*#__PURE__*/ Fse(/*#__PURE__*/ F(/* @__PURE__ */ Ose((e,t,n,r)=>{let i=r.getRef(kN),a=ca(r.context,AN)??{},o=a.headers?yg(hg(a.headers),e.headers):e.headers;o[`content-length`]&&(o=bg(o,`content-length`));let s=r=>V(Xf({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:typeof ReadableStream<`u`&&r instanceof ReadableStream?`half`:void 0,signal:n}),catch:t=>new iA({reason:new cA({request:e,cause:t})})}),t=>mse(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return B(ZE(e.body.stream),s)}return s(void 0)}))),Cue=/*#__PURE__*/ new Set(typeof Ot.zstdCompress==`function`?[`gzip`,`deflate`,`br`,`zstd`]:[`gzip`,`deflate`,`br`]),MN=(e,t)=>{let n={};return e!==void 0&&(n[Ot.constants.BROTLI_PARAM_QUALITY]=e),t!==void 0&&(n[Ot.constants.BROTLI_PARAM_SIZE_HINT]=t),{params:n}},NN=e=>e===void 0||e===3?void 0:{params:{[Ot.constants.ZSTD_c_compressionLevel]:e}},wue=(e,t,n)=>$f(r=>{let i=(e,t)=>r(e===null?F(t):rp(e));switch(t){case`gzip`:Ot.gzip(e,{level:n?.level},i);break;case`deflate`:Ot.deflate(e,{level:n?.level},i);break;case`br`:Ot.brotliCompress(e,MN(n?.level,e.byteLength),i);break;case`zstd`:{let t=NN(n?.level);t===void 0?Ot.zstdCompress(e,i):Ot.zstdCompress(e,t,i);break}}}),Tue=e=>({algorithms:e.algorithms,compressResponse(t,n,r){let i=t.body;return i._tag===`Uint8Array`?V(wue(i.body,n,r),e=>pj(vj(t,qk(e,t.headers[`content-type`]??i.contentType)),`content-length`,e.byteLength.toString())):e.compressResponse(t,n,r)}}),PN=(e,t)=>{switch(e){case`gzip`:return Ot.createGzip({level:t?.level,flush:Ot.constants.Z_SYNC_FLUSH});case`deflate`:return Ot.createDeflate({level:t?.level,flush:Ot.constants.Z_SYNC_FLUSH});case`br`:return Ot.createBrotliCompress({...MN(t?.level),flush:Ot.constants.BROTLI_OPERATION_FLUSH});case`zstd`:return Ot.createZstdCompress({...NN(t?.level),flush:Ot.constants.ZSTD_e_flush})}},FN=(e,t)=>{let n;return new St({read(){if(n===void 0){try{n=e()}catch(e){this.destroy(e instanceof Error?e:Error(String(e)));return}n.on(`data`,e=>{this.push(e)||n.pause()}),n.once(`end`,()=>this.push(null)),n.once(`error`,e=>this.destroy(e)),n.once(`close`,()=>{n.readableEnded||this.destroy(/* @__PURE__ */ Error(`Response stream closed prematurely`))})}n.resume()},destroy(e,r){n?.destroy(e??void 0),t?.(),r(e)}})},IN=(e,t)=>mj(vj(e,t),`content-length`),Eue=/*#__PURE__*/ fce({platform:`node`,compression:/* @__PURE__ */ Tue({algorithms:Cue,compressResponse(e,t,n){let r=e.body;switch(r._tag){case`Stream`:return F(IN(e,nA(Tk(r.stream,{evaluate:()=>PN(t,n)}),e.headers[`content-type`]??r.contentType)));case`Raw`:{let i=r.body instanceof St?r.body:void 0,a=FN(()=>{let e=PN(t,n);return i??=St.fromWeb(new Response(r.body).body),Ct(i,e,e=>{e&&a.destroy(e)})},()=>i?.destroy());return F(IN(e,Gk(a,{contentType:e.headers[`content-type`]??r.contentType})))}default:return F(e)}}}),fileResponse(e,t,n,r,i,a,o){let s=FN(()=>o===BigInt(0)?St.from([]):Et.createReadStream(e,{start:i,end:a===void 0?void 0:a-1}));return dj(s,{headers:{...r,"content-type":r[`content-type`]??Fi(Cj(e),()=>`application/octet-stream`),"content-length":o.toString()},status:t,statusText:n})},fileWebResponse(e,t,n,r,i){return dj(FN(()=>St.fromWeb(e.stream())),{headers:yg(r,gg({"content-type":r[`content-type`]??(e.type===``?Fi(Cj(e.name),()=>`application/octet-stream`):e.type),"content-length":e.size.toString()})),status:t,statusText:n})}}),Due=/*#__PURE__*/ zt(/*#__PURE__*/ pf(wj)(Eue),/*#__PURE__*/ Cf(DN),/*#__PURE__*/ Cf(Zse));var Oue=class extends bt{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,n;this._parser=Rce({...e,onField:(e,n)=>{if(t!==void 0)return;let r={_tag:`Field`,info:e,value:n};this.push(r),this.emit(`field`,r)},onFile:e=>{if(t!==void 0)return e=>{};let r=new Aue(e,this);return n=r,this.push(r),this.emit(`file`,r),e=>{t===void 0&&(this._canWrite=r.push(e),e===null&&!this._canWrite&&(n=void 0,this._resume()))}},onError:e=>{this.emit(`error`,e),n?.emit(`error`,e),t=e},onDone:()=>{this.push(null)}})}_resume(){if(this._canWrite=!0,this._writeCallback!==void 0){let e=this._writeCallback;this._writeCallback=void 0,e()}}_read(e){}_write(e,t,n){this._parser.write(e instanceof Uint8Array?e:Buffer.from(e,t)),this._canWrite?n():this._writeCallback=n}_final(e){this._parser.end(),e()}};const kue=e=>new Oue(e);var Aue=class extends St{_tag=`File`;filename;info;_parent;constructor(e,t){super(),this.info=e,this._parent=t,this.filename=e.filename}_read(e){this._parent._canWrite===!1&&this._parent._resume()}};const LN=(e,t)=>Gce(t).pipe(V(t=>Sk({evaluate(){let n=kue(t);return e.pipe(n),n},onError:e=>Fue(e)})),DE,OE(Mue)),jue=(e,t)=>Xce(LN(e,t),(e,t)=>Xf({try:n=>mee.pipeline(t.file,Et.createWriteStream(e),{signal:n}),catch:e=>nM.fromReason(`InternalError`,e)})),Mue=e=>e._tag===`Field`?new Nue(e.info,e.value):new Pue(e);var RN=class extends tr{[eM];constructor(){super(),this[eM]=eM}},Nue=class extends RN{_tag=`Field`;key;contentType;value;constructor(e,t){super(),this.key=e.name,this.contentType=e.contentType,this.value=Bce(e,t)}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`Field`,key:this.key,value:this.value,contentType:this.contentType}}},Pue=class extends RN{_tag=`File`;key;name;contentType;content;contentEffect;file;constructor(e){super(),this.file=e,this.key=e.info.name,this.name=e.filename??e.info.name,this.contentType=e.info.contentType,this.content=Sk({evaluate:()=>e,onError:e=>nM.fromReason(`InternalError`,e)}),this.contentEffect=Dk(()=>e,{onError:e=>nM.fromReason(`InternalError`,e)})}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`File`,key:this.key,name:this.name,contentType:this.contentType}}};function Fue(e){switch(e._tag){case`ReachedLimit`:switch(e.limit){case`MaxParts`:return nM.fromReason(`TooManyParts`,e);case`MaxFieldSize`:return nM.fromReason(`FieldTooLarge`,e);case`MaxPartSize`:return nM.fromReason(`FileTooLarge`,e);case`MaxTotalSize`:return nM.fromReason(`BodyTooLarge`,e)}default:return nM.fromReason(`Parse`,e)}}const zN=e=>({fromFileUrl:t=>ip({try:()=>ht.fileURLToPath(t,{windows:e}),catch:e=>new kT({module:`Path`,method:`fromFileUrl`,cause:e})}),toFileUrl:t=>ip({try:()=>ht.pathToFileURL(t,{windows:e}),catch:e=>new kT({module:`Path`,method:`toFileUrl`,cause:e})})});({...ut.posix,.../*#__PURE__*/ zN(!1)}),{...ut.win32,.../*#__PURE__*/ zN(!0)};const Iue=/* @__PURE__ */ uf(iD)(/*#__PURE__*/ aD({...ut,.../*#__PURE__*/ zN(void 0)})),Lue=/* @__PURE__ */ uf(UO,/*#__PURE__*/ WO({args:/*#__PURE__*/ I(()=>process.argv.slice(2)),stdinIsTerminal:/*#__PURE__*/ I(()=>process.stdin.isTTY===!0),stdoutIsTerminal:/*#__PURE__*/ I(()=>process.stdout.isTTY===!0),stderrIsTerminal:/*#__PURE__*/ I(()=>process.stderr.isTTY===!0),stdout:e=>yk({evaluate:()=>process.stdout,onError:e=>MT({module:`Stdio`,method:`stdout`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stderr:e=>yk({evaluate:()=>process.stderr,onError:e=>MT({module:`Stdio`,method:`stderr`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stdin:/*#__PURE__*/ Sk({evaluate:()=>process.stdin,onError:e=>MT({module:`Stdio`,method:`stdin`,_tag:`Unknown`,cause:e}),closeOnDone:!1})})),Rue=/*#__PURE__*/ pf(JO,/*#__PURE__*/ (/* @__PURE__ */ H(function*(e=BN){let t=process.stdin,n=process.stdout,r=yield*GC(),i=t.readableEnded,a=!1,o=()=>{i=!0,a||tw(r)};t.once(`end`,o),yield*Vp(()=>I(()=>t.off(`end`,o)));let s=yield*dE({acquire:Bp(I(()=>{let e=kt.createInterface({input:t,escapeCodeTimeout:50}),n=e=>YC(r,e),i=()=>{a=!1,tw(r)};return a=!0,kt.emitKeypressEvents(t,e),e.on(`line`,n),e.once(`close`,i),t.isTTY&&t.setRawMode(!0),{rl:e,onClose:i,onLine:n}}),({rl:e,onClose:n,onLine:o})=>I(()=>{a=!1,e.off(`line`,o),e.off(`close`,n),t.isTTY&&t.setRawMode(!1),e.close(),i&&tw(r)})),idleTimeToLive:`10 millis`}),c=I(()=>n.columns??0),l=I(()=>n.rows??0),u=R(function*(){let n=yield*GC(),r=(t,r)=>{let i={input:Ri(t),key:{name:r.name??``,ctrl:!!r.ctrl,meta:!!r.meta,shift:!!r.shift}};YC(n,i),e(i)&&tw(n)},a=setInterval(()=>{},2147483647),o=()=>{clearInterval(a),tw(n)};return yield*Vp(()=>I(()=>{clearInterval(a),t.off(`keypress`,r),t.off(`end`,o)})),t.on(`keypress`,r),i?o():(yield*fE(s),t.once(`end`,o)),n}),d=Qf(()=>cw(r).pipe(B(Pi({onNone:()=>zp(sp(fE(s),sw(r))),onSome:F})),vp(()=>new qO({}))));return YO({columns:c,rows:l,readInput:u,readLine:d,display:e=>Xp($f(t=>{n.write(e,e=>rn(e)?t(L):t(z(NT({module:`Terminal`,method:`display`,description:`Failed to write prompt to stdout`,cause:e}))))}))})}))(BN));function BN(e){let t=e.key;return t.name===`escape`||t.ctrl&&(t.name===`c`||t.name===`d`)}const zue=/*#__PURE__*/ wf(Lk,/*#__PURE__*/ bf(DN,qle,Iue,Lue,Rue)),Bue=(e,t)=>{let n=lle(e,Wue,t.middleware);return ap(e=>{let r=e.context;return F(function(i,a){let o=oa(r,lM,new Vue(i,a)),s=$S(om(o)(n),t.scope);s.pollUnsafe()===void 0&&a.on(`close`,()=>{a.writableEnded||s.interruptUnsafe(e.id,Pj.annotation)})})})};var Vue=class e extends Sue{[cM];response;upgradeEffect;upgraded=!1;url;headersOverride;constructor(e,t,n,r=e.url,i,a){super(e,e=>new jj({reason:new Mj({request:this,cause:e})}),a),this[cM]=cM,this.response=t,this.upgradeEffect=n,this.url=r,this.headersOverride=i}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=eg(this.headers.cookie??``)}get resolvedResponse(){return typeof this.response==`function`?this.response():this.response}modify(t){return new e(this.source,this.response,this.upgradeEffect,t.url??this.url,t.headers??this.headersOverride,`remoteAddress`in t?t.remoteAddress:this.remoteAddressOverride)}get originalUrl(){return this.source.url}cachedMethod;get method(){return this.cachedMethod??=this.source.method.toUpperCase()}get headers(){return this.headersOverride??=this.source.headers,this.headersOverride}multipartEffect;get multipart(){return this.multipartEffect||=cm(Kp(jue(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return LN(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??z(new jj({reason:new Mj({request:this,description:`not an upgradeable ServerRequest`})}))}toString(){return`ServerRequest(${this.method} ${Vg(this.url)})`}toJSON(){return OA(this,{_id:`HttpServerRequest`,method:this.method,url:Vg(this.originalUrl)})}};const Hue=/*#__PURE__*/ bf(Due,Qse,zue),Uue=/*#__PURE__*/ aj({status:101}),Wue=(e,t)=>{if(e.upgraded)return F(Uue);let n=e.resolvedResponse;if(n.writableEnded)return L;let r=t.headers;if(!Bh(t.cookies)){r={...r};let e=$h(t.cookies);r[`set-cookie`]!==void 0&&e.push(r[`set-cookie`]),r[`set-cookie`]=e}if(e.method===`HEAD`)return n.writeHead(t.status,t.statusText,r),sp(Gue(t.body),$f(e=>{let t=!1,r=()=>{t||(t=!0,n.off(`close`,r),e(L))};n.once(`close`,r),n.end(r)}));let i=t.body;switch(i._tag){case`Empty`:return n.writeHead(t.status,t.statusText,r),n.end(),L;case`Raw`:return n.writeHead(t.status,t.statusText,r),typeof i.body==`object`&&i.body!==null&&`pipe`in i.body&&typeof i.body.pipe==`function`?Xf({try:e=>hee(i.body,n,{signal:e,end:!0}),catch:n=>new jj({reason:new Nj({request:e,response:t,description:`Error writing raw response`,cause:n})})}).pipe(Jp,xp(VN(n,t))):$f(e=>{n.end(i.body,()=>e(L))});case`Uint8Array`:return n.writeHead(t.status,t.statusText,r),i.contentLength<1048576?(n.end(i.text??i.body),L):$f(e=>{n.end(i.text??i.body,()=>e(L))});case`FormData`:return Qf(()=>{let a=new globalThis.Response(i.formData);return n.writeHead(t.status,t.statusText,{...r,...Object.fromEntries(a.headers)}),$f((r,i)=>{St.fromWeb(a.body,{signal:i}).pipe(n).on(`error`,n=>{r(z(new jj({reason:new Nj({request:e,response:t,description:`Error writing FormData response`,cause:n})})))}).once(`finish`,()=>{r(L)})}).pipe(Jp,xp(VN(n,t)))});case`Stream`:{n.writeHead(t.status,t.statusText,r);let e=eC();return n.on(`drain`,()=>e.openUnsafe()),i.stream.pipe(IE,JE(t=>{let r=t.length>1?Buffer.concat(t):t[0];return n.write(r)?L:(e.closeUnsafe(),e.await)}),Jp,Op({onSuccess:()=>I(()=>n.end()),onFailure:VN(n,t)}))}}},Gue=e=>{let t=e._tag===`Raw`?e.body:void 0;return t instanceof St?I(()=>t.destroy()):L},VN=(e,t)=>n=>B(Lj(n),([r,i])=>{let a=e.headersSent;return a||e.writeHead(r.status,r.statusText),e.writableEnded||e.end(),tp(a?cre(n,pd(t)):i)}),Kue={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},que=e=>Kue[e],HN=new TextEncoder,UN=new TextDecoder,WN=new TextDecoder(`utf-8`,{fatal:!0}),GN=2**32;function KN(...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}function qN(e,t,n){if(t<0||t>=GN)throw RangeError(`value must be >= 0 and <= ${GN-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function JN(e){let t=Math.floor(e/GN),n=e%GN,r=/* @__PURE__ */ new Uint8Array(8);return qN(r,t,0),qN(r,n,4),r}function YN(e){let t=/* @__PURE__ */ new Uint8Array(4);return qN(t,e),t}const Jue=/[^\x00-\x7f]/;function XN(e){if(typeof e==`string`&&e.length>=128){if(Jue.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return HN.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Yue(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function Xue(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function ZN(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var QN=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},$N=class extends QN{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},eP=class extends QN{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},tP=class extends QN{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},nP=class extends QN{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},rP=class extends QN{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},iP=class extends QN{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},aP=class extends QN{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},oP=class extends QN{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},sP=class extends QN{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},cP=class extends QN{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},lP=class extends QN{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},uP=class extends QN{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},dP=class extends QN{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},fP=class extends QN{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function pP(e){try{return Xue(typeof e==`string`?e:UN.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function mP(e){return Yue(typeof e==`string`?HN.encode(e):e,!0)}function hP(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function gP(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function _P(e){return gP(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(gP)}function vP(...e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function yP(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function bP(e,t,n){try{return pP(e)}catch(e){throw new n(`Failed to base64url decode the ${t}`,{cause:e})}}function xP(e,t,n){try{return XN(e)}catch(e){throw new n(`The ${t} is not a valid base64url string`,{cause:e})}}function SP(e,t,n){let r;try{r=JSON.parse(WN.decode(pP(e)))}catch(e){throw new t(n,{cause:e})}if(!gP(r))throw new t(n);return r}const CP={__proto__:null,b64:!0},wP={__proto__:null};function TP(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`);return t===void 0?void 0:new Set(t)}function EP(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function DP(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[];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=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new nP(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function OP(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new aP(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function kP(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!gP(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}const Zue=e=>e[Symbol.toStringTag],Que=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function AP(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(gP(t)){if(o=WP(t),typeof o.kty!=`string`)throw RP(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Que(e,o,n),o.kty===`oct`)return pP(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!FP(t))throw RP(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Zue(t)} instances must be of type "${e}" for the ${r} algorithm`);if(NP(t))return t;if(s=t,s.type===`secret`)return s.export()}jP||=/* @__PURE__ */ new WeakMap;let c=t,l=jP.get(c);if(l?.[r])return l[r];if(l||jP.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=$ue[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await KP(e,o)}let jP;const $ue={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function MP(e){if(!NP(e))throw Error(`CryptoKey instance expected`)}const NP=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},PP=e=>e?.[Symbol.toStringTag]===`KeyObject`,FP=e=>NP(e)||PP(e);function IP(e,t,...n){if(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}const LP=(e,...t)=>IP(`Key must be `,e,...t);function RP(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(IP(`Key for the ${e} algorithm must be `,t,...r))}const zP=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function BP(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function VP(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function HP(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw zP(t.name);if(t.hash&&r.hash?.name!==t.hash)throw zP(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw zP(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw zP(t.length,`algorithm.length`);BP(e,n)}function UP(e){return{__proto__:null,...e}}function WP(e){let t=UP(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function GP(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function KP(e,t,n){if(!e.kty.includes(t.kty))throw new nP(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function qP(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),HP(e,t,n),e}const JP=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function YP(e,t){let n=e.byteLength<<3;if(n!==t)throw new iP(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}const ede=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function XP(e,t){if(t.length<<3!==e.ivBits)throw new iP(`Invalid Initialization Vector length`)}async function ZP(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(LP(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function QP(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function tde(e,t,n,r,i){let[a,o,s]=await ZP(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await QP(o,KN(i,r,c,JN(i.length*8)),s),iv:r}}async function nde(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function rde(e,t,n,r,i,a){let[o,s,c]=await ZP(e,t,`decrypt`),l=await QP(s,KN(a,r,n,JN(a.length*8)),c);try{if(await nde(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new rP}async function $P(e,t,n,r,i){if(!NP(n)&&!(n instanceof Uint8Array))throw TypeError(LP(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?XP(e,r):r=ede(e),n instanceof Uint8Array&&YP(n,e.cekBits),e.cbc)return tde(e,t,n,r,i);let a=await qP(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function eF(e,t,n,r,i,a){if(!NP(t)&&!(t instanceof Uint8Array))throw TypeError(LP(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new iP(`JWE Initialization Vector missing`);if(!i)throw new iP(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new iP(`Invalid Authentication Tag length`);if(XP(e,r),t instanceof Uint8Array&&YP(t,e.cekBits),e.cbc)return rde(e,t,n,r,i,a);let o=await qP(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,KN(n,i)))}catch{throw new rP}}function tF(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const ide=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],ade=[[],[`deriveBits`]],nF=[[],[]];function rF(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:ide,ops:[`wrapKey`,`unwrapKey`]}}function iF(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new nP(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:ade,ops:[void 0,`deriveBits`]}}function aF(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:nF,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function oF(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:nF,ops:[`deriveBits`,`deriveBits`]}}const sF=tF({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:nF,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":rF(1),"RSA-OAEP-256":rF(256),"RSA-OAEP-384":rF(384),"RSA-OAEP-512":rF(512),"ECDH-ES":iF(`direct-key-agreement`),"ECDH-ES+A128KW":iF(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":iF(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":iF(`key-agreement-with-key-wrapping`),A128KW:aF(128),A192KW:aF(192),A256KW:aF(256),A128GCMKW:aF(128,!0),A192GCMKW:aF(192,!0),A256GCMKW:aF(256,!0),"PBES2-HS256+A128KW":oF(),"PBES2-HS384+A192KW":oF(),"PBES2-HS512+A256KW":oF()}),ode=[`encrypt`,`decrypt`];function cF(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:nF,ops:ode,cekBits:e,ivBits:t?128:96,cbc:t}}const sde=tF({A128GCM:cF(128),A192GCM:cF(192),A256GCM:cF(256),"A128CBC-HS256":cF(256,!0),"A192CBC-HS384":cF(384,!0),"A256CBC-HS512":cF(512,!0)});function lF(e,t){throw new nP(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function uF(e){return(typeof e==`string`?sF[e]:void 0)??lF(`alg`,`Algorithm`)}function dF(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function fF(e){return(typeof e==`string`?sde[e]:void 0)??lF(`enc`,`Encryption Algorithm`)}function pF(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);BP(e,t)}async function cde(e,t,n){let r=await qP(t,uF(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function lde(e,t,n){let r=await qP(t,uF(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function mF(e,t,n){HP(t,uF(e).subtle,n),VP(e,t)}async function hF(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new iP(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new iP(`PBES2 Count Input must be a positive integer`);let i=KN(XN(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await qP(r,uF(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function gF(e){return KN(YN(e.length),e)}async function ude(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await ZN(`sha256`,KN(YN(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function _F(e,t,n,r,i=/* @__PURE__ */ new Uint8Array,a=/* @__PURE__ */ new Uint8Array){pF(e),pF(t,`deriveBits`);let o=KN(gF(XN(n)),gF(i),gF(a),YN(r));return ude(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function vF(e){MP(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new nP(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function yF(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new iP(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return bP(n,t,iP)}}function bF(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new iP(`JOSE Header "apu" and "apv" values must be distinct`)}}function dde(e){if(e===void 0)throw new iP(`JWE Encrypted Key missing`)}function xF(e){if(e!==void 0)throw new iP(`Encountered unexpected JWE Encrypted Key`)}function fde(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function pde(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return xF(r),n;let c=s===`direct-key-agreement`;switch(c?xF(r):dde(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!gP(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new iP(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);vF(n);let a=await KP(e,r),s=yF(i,`apu`),l=yF(i,`apv`);bF(s,l);let u=await _F(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return MP(n),mF(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new iP(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);fde(a);let e=a??1e4;if(i.p2c>e)throw new iP(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new iP(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await hF(bP(i.p2s,`p2s`,iP),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new iP(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new iP(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=bP(i.iv,`iv`,iP),t=bP(i.tag,`tag`,iP);if(e.byteLength!==12)throw new iP(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new iP(`Invalid Authentication Tag length`);return eF(fF(o.slice(0,-2)),n,r,e,t,/* @__PURE__ */ new Uint8Array)}}return lde(o.slice(-6),n,r)}async function mde(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=dF(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await AP(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??JP(t):void 0;u&&YP(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{vF(l);let{apu:n,apv:i}=a;n!==void 0&&hP(n,`"apu"`),i!==void 0&&hP(i,`"apv"`);let c=n??yF(r,`apu`),u=i??yF(r,`apv`);bF(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await AP(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await _F(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=mP(n)),i!==void 0&&(f.apv=mP(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:MP(l),mF(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))}=a;l=await hF(t,o,e,l),f={p2c:e,p2s:mP(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await $P(fF(o.slice(0,-2)),u,l,e,/* @__PURE__ */ new Uint8Array);d=t.ciphertext,f={iv:mP(t.iv),tag:mP(t.tag)}}}if(d??=await cde(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function SF(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new nP(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new iP(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function CF(e){if(typeof globalThis[e]>`u`)throw new nP(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function wF(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=e.readable.getReader();for(;;){let{value:e,done:t}=await o.read();if(t)break;if(i.push(e),a+=e.byteLength,n!==1/0&&a>n)throw new iP(`Decompressed plaintext exceeded the configured limit`)}return KN(...i)}async function hde(e){return CF(`CompressionStream`),wF(new CompressionStream(`deflate-raw`),e)}async function gde(e,t){return CF(`DecompressionStream`),wF(new DecompressionStream(`deflate-raw`),e,t)}function _de(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=SP(t,iP,`JWE Protected Header is invalid`)),[o,bP(n,`ciphertext`,iP),r===void 0?void 0:bP(r,`iv`,iP),i===void 0?void 0:bP(i,`tag`,iP),xP((t??``)+(a===void 0?``:`.${a}`),`aad`,iP)]}function vde(e){return[e&&TP(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&TP(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function yde(e,t,n,r=_de(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!vP(i,l,u))throw new iP(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:v}=e;DP(iP,wP,h,i,f),SF(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new iP(`missing JWE Algorithm (alg) in JWE Header`);let x=sF[y];if(v===``&&(!x||!dF(x)))throw new iP(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new iP(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new tP(`"alg" (Algorithm) Header Parameter value not allowed`);let ee;if(S){if(b!==void 0)throw new iP(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new iP(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new iP(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new tP(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);ee=fF(b)}let C;if(v!==void 0)try{C=bP(v,`encrypted_key`,iP)}catch(e){if(!x||!dF(x))throw e;C=/* @__PURE__ */ new Uint8Array}let te=!1;typeof n==`function`&&(n=await n(i,e),te=!0);let w=x??uF(y);dF(w)&&C===void 0&&(C=/* @__PURE__ */ new Uint8Array);let ne=await AP(w.mode===`direct-encryption`?ee:w,n,`decrypt`),T;if(w.mode===`integrated-encryption`)T=await w.decrypt(ne,C,a,c,i,f);else{let e=ee,t;try{t=await pde(w,e,ne,C,f,g),dF(w)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=JP(e))}catch(n){if(n instanceof TypeError||n instanceof iP||n instanceof nP)throw n;t=JP(e)}T=await eF(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new nP(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);T=await gde(T,e).catch(e=>{throw e instanceof iP?e:new iP(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:T,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:bP(d,`aad`,iP)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...te&&{key:ne}}}async function bde(e,t,n){if(e instanceof Uint8Array&&(e=UN.decode(e)),typeof e!=`string`)throw new iP(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new iP(`Invalid Compact JWE`);return yde({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function TF(e,t,n){if(!vP(e,t,n))throw new iP(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function xde(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new iP(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&hP(o,`JWE Additional Authenticated Data`),s!==void 0&&hP(s,`JWE Content Encryption Key`),c!==void 0&&hP(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=kP(iP,r)[0],e[1]=r),i!==void 0&&(i=kP(iP,i)[0],e[2]=i),!n&&a!==void 0&&(a=kP(iP,a)[0],e[3]=a),l!==void 0&&!gP(l))throw TypeError(`JWE Key Management Parameters must be an object`);TF(r,i,a);let d={...r,...i,...a};EP(iP,r),DP(iP,wP,u,r,d),SF(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new iP(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=sF[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new iP(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new iP(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,fF(p),m]}async function Sde(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??uF(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await AP(_,n,`encrypt`):[b,v,y]=await mde(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,TF(h,g,l));let x=h?mP(JSON.stringify(h)):``,S=u?.byteLength?mP(u):void 0,ee=XN(S?`${x}.${S}`:x),C=o;r.zip===`DEF`&&(C=await hde(C).catch(e=>{throw new iP(`Failed to compress plaintext`,{cause:e})}));let te,w,ne;_.mode===`integrated-encryption`?[v,te]=await _.encrypt(b,C,ee,h,r,p):{ciphertext:te,tag:w,iv:ne}=await $P(i,C,b,f,ee);let T={ciphertext:mP(te)};return ne&&(T.iv=mP(ne)),w&&(T.tag=mP(w)),v?.byteLength&&(T.encrypted_key=mP(v)),S&&(T.aad=S),h&&(T.protected=x),l&&(T.unprotected=l),g&&(T.header=g),T}async function Cde(e,t,n){return Sde(e,xde(e,n),t)}function wde(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}const EF=[[`verify`],[`sign`]];function DF(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:EF}}function OF(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:EF,minRsaBits:2048}}function kF(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:EF}}function AF(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:EF}}function jF(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:EF}}const MF=tF({HS256:DF(256),HS384:DF(384),HS512:DF(512),RS256:OF(256),RS384:OF(384),RS512:OF(512),PS256:OF(256,32),PS384:OF(384,48),PS512:OF(512,64),ES256:kF(`P-256`,256),ES384:kF(`P-384`,384),ES512:kF(`P-521`,512),EdDSA:AF(),Ed25519:AF(),"ML-DSA-44":jF(44),"ML-DSA-65":jF(65),"ML-DSA-87":jF(87)});function NF(e){let t=typeof e==`string`?MF[e]:void 0;if(!t)throw new nP(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function PF(e){return[e&&TP(`algorithms`,e.algorithms),e?.crit]}function Tde(e){return e===void 0?{}:SP(e,aP,`JWS Protected Header is invalid`)}function Ede(e){try{return XN(e)}catch(e){throw new aP(`JWS Compact Serialization payload must use only ASCII characters`,{cause:e})}}async function Dde(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??Tde(a);if(!vP(c,o))throw new aP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=OP(c,DP(aP,CP,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new aP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new tP(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new aP(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new aP(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=NF(d),h=KN(a===void 0?/* @__PURE__ */ new Uint8Array:XN(a),XN(`.`),typeof f==`string`?t[2]??=xP(f,`payload`,aP):f),g=bP(e.signature,`signature`,aP),_=await AP(m,n,`verify`),v=await qP(_,m.subtle,`verify`);m.minRsaBits&&VP(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch(e){throw new fP(void 0,{cause:e})}if(!y)throw new fP;let b={payload:typeof f==`string`?bP(f,`payload`,aP):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function FF(e,t,n){if(e instanceof Uint8Array&&(e=UN.decode(e)),typeof e!=`string`)throw new aP(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new aP(`Invalid Compact JWS`);return Dde({payload:i,protected:r,signature:a},t,n,Ede)}async function IF(e,t,n){let[r]=await FF(e,PF(n),t);return r}const LF=e=>Math.floor(e.getTime()/1e3),Ode={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},kde=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,RF=`check_failed`;function zF(){throw TypeError(`Invalid time period format`)}function BF(e){typeof e!=`string`&&zF();let t=kde.exec(e);(!t||t[4]&&t[1])&&zF();let n=parseFloat(t[2]),r=Math.round(n*Ode[t[3][0].toLowerCase()]);return Number.isFinite(r)||zF(),t[1]===`-`||t[4]===`ago`?-r:r}function VF(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function HF(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Ade(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function UF(e,t){return typeof e==`number`?VF(t,e):e instanceof Date?VF(t,LF(e)):LF(/* @__PURE__ */ new Date)+BF(e)}const WF=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},jde=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function GF(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new $N(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function KF(e,t){throw new $N(`unexpected "${t}" claim value`,e,t,RF)}function qF(e,t,n={}){let r;try{r=JSON.parse(WN.decode(t))}catch(e){throw new oP(`JWT Claims Set must be a top-level JSON object`,{cause:e})}if(!gP(r))throw new oP(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||WF(e.typ)!==WF(i)))throw new $N(`unexpected "typ" JWT header value`,r,`typ`,RF);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(!Object.hasOwn(r,e))throw new $N(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&KF(r,`iss`),s!==void 0&&r.sub!==s&&KF(r,`sub`),c!==void 0&&!jde(r.aud,typeof c==`string`?[c]:c)&&KF(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=BF(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}VF(`clockTolerance option`,f);let{currentDate:p}=n,m=VF(`currentDate option`,LF(p===void 0?/* @__PURE__ */ new Date:p)),h=GF(r,`iat`,l!==void 0),g=GF(r,`nbf`);if(g!==void 0&&g>m+f)throw new $N(`"nbf" claim timestamp check failed`,r,`nbf`,RF);let _=GF(r,`exp`);if(_!==void 0&&_<=m-f)throw new eP(`"exp" claim timestamp check failed`,r,`exp`,RF);if(l!==void 0){let e=m-h,t=VF(`maxTokenAge option`,typeof l==`number`?l:BF(l));if(e-f>t)throw new eP(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,RF);if(e<-f)throw new $N(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,RF)}return r}let JF;function YF(e){return JF.get(e)}function XF(e){let t=YF(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return HN.encode(JSON.stringify(t))}function ZF(e,t){return YF(e)[t]}var QF=class{constructor(e={}){if(!gP(e))throw TypeError(`JWT Claims Set MUST be an object`);(JF||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return HF(`iss`,e),YF(this).iss=e,this}setSubject(e){return HF(`sub`,e),YF(this).sub=e,this}setAudience(e){return Ade(e),YF(this).aud=e,this}setJti(e){return HF(`jti`,e),YF(this).jti=e,this}setNotBefore(e){return YF(this).nbf=UF(e,`setNotBefore`),this}setExpirationTime(e){return YF(this).exp=UF(e,`setExpirationTime`),this}setIssuedAt(e){let t=YF(this);return t.iat=e===void 0?LF(/* @__PURE__ */ new Date):typeof e==`string`?VF(`setIssuedAt`,LF(/* @__PURE__ */ new Date)+BF(e)):UF(e,`setIssuedAt`),this}};async function $F(e,t,n){let[r,i]=await FF(e,PF(n),t);if(!i)throw new oP(`JWTs MUST NOT use unencoded payload`);let a=qF(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function eI(e,t,n){let{plaintext:r,...i}=await bde(e,vde(n),t),{protectedHeader:a}=i,o=qF(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new $N(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function Mde(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=kP(aP,i);i=e[0],s=mP(e[1])}if(a!==void 0&&(a=kP(aP,a)[0]),!i&&!a)throw new aP(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!vP(i,a))throw new aP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};EP(aP,i);let l=OP(i,DP(aP,CP,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new aP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=NF(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=mP(r),p=t[1]??=XN(f)):(f=mP(r),m=HN.encode(`${s}.${f}`))}m??=KN(XN(s),XN(`.`),p);let h=await qP(await AP(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&VP(d.alg,h);let g={signature:mP(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function Nde(e,t,n,r,i){let[a]=await Mde([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const Pde=QF;var tI=class extends Pde{#e;setProtectedHeader(e){return yP(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Nde(XF(this),this.#e,t?.crit,e,()=>{throw new oP(`JWTs MUST NOT use unencoded payload`)})}};const Fde=QF;var Ide=class extends Fde{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return yP(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return yP(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return yP(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return yP(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=XF(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?ZF(this,`iss`):void 0,sub:this.#n?ZF(this,`sub`):void 0,aud:this.#r?ZF(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,wde(await Cde(r,e,t))}};function nI(e=`JWK "alg" (Algorithm) Parameter`){throw new nP(`Invalid or unsupported ${e} value`)}function rI(e,t){return(typeof e==`string`?MF[e]??sF[e]:void 0)??nI(t)}async function iI(e){if(PP(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:mP(e)};if(!NP(e))throw TypeError(LP(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}const aI=(e,t)=>{if(typeof e!=`string`||!e)throw new sP(`${t} missing or invalid`)};async function oI(e,t){let n;if(gP(e)){if(n=UP(e),typeof n.kty!=`string`)throw TypeError(LP(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(FP(e))n=UP(await iI(e));else throw TypeError(LP(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:aI(n.alg,`"alg" (Algorithm) Parameter`),aI(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:aI(n.crv,`"crv" (Curve) Parameter`),aI(n.x,`"x" (X Coordinate) Parameter`),aI(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:aI(n.crv,`"crv" (Subtype of Key Pair) Parameter`),aI(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:aI(n.e,`"e" (Exponent) Parameter`),aI(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new sP(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new nP(`"kty" (Key Type) Parameter missing or unsupported`)}let i=XN(JSON.stringify(r));return mP(await ZN(t,i))}function Lde(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function sI(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=KP(n,t,!0).then(e=>{if(e.type!==`public`)throw new cP(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function cI(e){let t;try{t=structuredClone(e)}catch(e){throw new cP(`JSON Web Key Set malformed`,{cause:e})}if(!_P(t))throw new cP(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=UP(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=/* @__PURE__ */ new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?MF[a]:void 0;if(!s||s.secret)throw new nP(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Lde(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new lP;if(u!==1){let e=new uP;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await sI(r,e,s)}catch{}},e}return sI(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Rde(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let lI;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(lI=`jose/v6.2.13`);const zde=/* @__PURE__ */ Symbol();async function Bde(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new dP(void 0,{cause:e}):e});if(i.status!==200)throw new QN(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch(e){throw new QN(`Failed to parse the JSON Web Key Set HTTP response as JSON`,{cause:e})}}const Vde=/* @__PURE__ */ Symbol();function uI(e,t){return Number.isFinite(e)&&Date.now()<e+t}function dI(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function Hde(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=dI(r.cooldownDuration,3e4,`cooldownDuration`),s=dI(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);lI&&!c.has(`User-Agent`)&&c.set(`User-Agent`,lI),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[zde],u=r[Vde],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;uI(e,s)&&_P(t)&&(d=e,h=cI(t))}let g=async()=>{if(f&&Rde()&&(f=void 0),!f){let e=++p,t=f=Bde(n,c,AbortSignal.timeout(a),l).then(t=>{let n=cI(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!uI(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof lP&&!uI(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>uI(d,o),enumerable:!0},fresh:{get:()=>uI(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}async function fI(e,t,n){if(!gP(e))throw TypeError(`JWK must be an object`);let r=WP(e),i=GP(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return pP(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return KP(rI(t),r,i);case`RSA`:case`EC`:case`OKP`:return KP(rI(t),r,i);default:throw new nP(`Unsupported "kty" (Key Type) Parameter value`)}}function pI(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return SP(t,TypeError,n)}function mI(e){if(typeof e!=`string`)throw new oP(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new oP(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new oP(`Invalid JWT`);if(!t)throw new oP(`JWTs must contain a payload`);let r;try{r=pP(t)}catch(e){throw new oP(`Failed to base64url decode the payload`,{cause:e})}let i;try{i=JSON.parse(WN.decode(r))}catch(e){throw new oP(`Failed to parse the decoded payload as JSON`,{cause:e})}if(!gP(i))throw new oP(`Invalid JWT Claims Set`);return i}function Ude(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new nP(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Wde(e,t){let n=GP(t?.extractable),r=rI(e,`"alg" (Algorithm)`);r.secret&&nI(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new nP(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new nP(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Ude(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}const hI=`key-list+jwt`,Gde=W({keys:G(W({id:U,sealed:U}))}),gI=bS(W({keyId:_S,ownerId:_S,scopes:G(_S),expiresAt:Zx(cS)})),_I=new TextEncoder,Kde=async e=>new Uint8Array(await crypto.subtle.digest(`SHA-256`,_I.encode(e))),vI=async(e,t)=>{let n=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveBits`]),r=new Uint8Array(await crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:/* @__PURE__ */ new Uint8Array,info:_I.encode(`clankerauth key list\0${t}`)},n,512));return{id:mP(r.subarray(0,32)),key:await crypto.subtle.importKey(`raw`,r.subarray(32),`AES-GCM`,!1,[`encrypt`,`decrypt`])}},qde=async(e,t,n)=>{let{id:r,key:i}=await vI(e,t),a=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a},i,_I.encode(kx(gI)(n))),s=new Uint8Array(a.length+o.byteLength);return s.set(a),s.set(new Uint8Array(o),a.length),{id:r,sealed:mP(s)}},Jde=async(e,t,n)=>{let r=await vI(await Kde(e),t),i=n.get(r.id);if(i===void 0)return;let a=new Uint8Array(pP(i)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.subarray(0,12)},r.key,a.subarray(12));return Tx(gI)(new TextDecoder().decode(o))},yI=Symbol.for(`@gjermundgaraba/effect-actions/Anyone`),bI=(e,t)=>{for(let n of e)if(n.caller!==yI&&(t===void 0||n.caller.key!==t.identity.key))throw Error(`Protected action '${n.name}' requires its matching authentication descriptor (give it the authentication whose identity the action's caller names)`)},xI=e=>U.pipe(eS(F(e))),Yde=W({path:G(K([U,cS])),message:U}),Xde=F_();var SI=class e extends US()(`InvalidInput`,{message:xI(`The input does not match the action's input.`),issues:G(Yde).pipe(eS(F([])))},{httpApiStatus:400}){static fromSchemaError=({issue:t,message:n})=>new e({message:n,issues:Xde(t).issues.map(e=>({path:(e.path??[]).map(e=>{let t=Qt(e)?e:e.key;return Zt(t)?String(t):t}),message:e.message}))})},CI=class extends US()(`Unauthenticated`,{message:xI(`Authentication is required.`)},{httpApiStatus:401}){};const wI=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Zde=U.check(sS(wI));var TI=class extends US()(`Forbidden`,{message:xI(`Not allowed.`),scopes:Mx(Jx(Zde))},{httpApiStatus:403}){};const EI=[CI,TI],Qde=K(EI),DI=[SI,...EI];K(DI);const OI=`[A-Za-z0-9_-]{1,128}`,$de=RegExp(`^${OI}$`),efe=e=>{if(!$de.test(e)||e===`then`)throw Error(`Invalid action name: ${e} (use ${OI}, other than "then")`)},kI=(e,t,n,{claimantOf:r=n,labelOf:i=n,fix:a})=>{let o=/* @__PURE__ */ new Map;for(let s of t){let t=n(s),c=o.get(t);if(c!==void 0){let t=[r(c),r(s)],n=t[0]===t[1]?``:`, claimed by ${t.join(` and `)}`;throw Error(`Duplicate ${e}: ${i(c)}${n} (${a})`)}o.set(t,s)}},AI=`pass one implementation of it, or rename one`,jI=(e,t,n=`list it once, or rename one`)=>kI(e,t,e=>e.name,{fix:n}),tfe=(e,t,n,r)=>{let i=t.filter(e=>!n.includes(e));if(i.length>0)throw Error(`Unknown ${e}: ${i.join(`, `)} (${r})`)},MI=e=>Ev(e)?MI(e.thunk()):e,NI=e=>{let t=MI(e);return Tv(t)?t.types.flatMap(NI):[t]},nfe=e=>xv(e)?[e.literal]:Lie(e)?e.enums.map(([,e])=>e):[void 0],PI=ob(`httpApiStatus`),FI=e=>PI(e)??(Ev(e)?FI(e.thunk()):void 0),II=e=>{let t=FI(e.ast);return t===void 0?e.annotate({httpApiStatus:422}):PI(e.ast)===void 0?e.annotate({httpApiStatus:t}):e},LI=e=>e===void 0?[]:jx(e)?[e]:e,rfe=e=>PI(e)===void 0&&e.checks===void 0&&e.encoding===void 0,RI=e=>rfe(e)?Ev(e)?RI(e.thunk()):Tv(e)?e.types.flatMap(RI):[e]:[e],zI=e=>{let t=/* @__PURE__ */ new Map;for(let n of e)for(let e of RI(n.ast))t.has(e)||t.set(e,e===n.ast?n:Ax(e));return[...t.values()]},BI=(e,t=[])=>zI([...DI,...e.error,...t]),VI=(e,t)=>BI(e,e.caller===yI||t.authentication===void 0?t.error:[...t.error,...t.authentication.error]),HI=e=>NI(Jy(e)).flatMap(e=>{let t=wv(e)?e.propertySignatures.find(e=>e.name===`_tag`)?.type:void 0;return t===void 0?[]:NI(t).flatMap(nfe).filter(Jt)}),ife=new Set(DI.flatMap(e=>HI(e.ast))),UI=(e,t)=>{let n=/* @__PURE__ */ new Set;for(let r of zI(t))for(let t of new Set(HI(r.ast))){if(n.has(t))throw Error(`${e}: error _tag "${t}" names two error schemas, which a client cannot tell apart (reuse one schema value, or merge them into one whose fields tell them apart${ife.has(t)?`; for a built-in's tag, fail with the built-in itself`:``})`);n.add(t)}},afe=(e,t,n)=>{jI(`action`,t);let r={error:LI(n.error),authentication:n.authentication};bI(t,r.authentication);for(let n of t)UI(`${e} of "${n.name}"`,VI(n,r));return r},ofe=()=>Math.random().toString(36).slice(2),WI=e=>{let t=P(`effect-actions/Implementation/${ofe()}`);return{key:t,layer:pf(t,e)}};var GI=class e{actions;#e;#t;constructor(e,t,n){this.actions=e,this.#e=t,this.#t=n}static share(t,n){let r=e.own(n);return new e(t,r.#e,r.#t)}static runKey(t){return e.own(t).#e.key.key}static layerOf(t){let n=e.own(t);return t.actions.some(e=>e.caller!==yI)?xf(n.#e.layer,n.#t.layer):n.#e.layer}static boundOf(t){let{actions:n}=t,r=e.own(t);return R(function*(){let e=yield*r.#e.key,t=n.some(e=>e.caller!==yI)?yield*r.#t.key:()=>L;return n.flatMap(n=>e.flatMap(([e,r])=>e===n?[[n,lfe(n,r,t)]]:[]))})}static own(e){if(!(#e in e))throw Error(`Not an implementation made by this Action.implement: pass the value implement returned, not a copy such as a spread; or effect-actions is installed twice`);return e}};const KI=e=>Aa(e),qI={byImplementation:{why:`no implementation holds it`,fix:`pass the implementation holding it, or list the contract it implements`,holder:`they do not hold: list the one they hold`},byBinding:{why:`the binding does not hold it`,fix:`add it to the binding's actions`,holder:`it does not hold: list the one it holds`}},JI=(e,t)=>e.map(({name:e})=>t.has(e)?`${e} (another contract)`:e).join(`, `),YI=({why:e,fix:t,holder:n},r,i)=>{let a=r.filter(e=>!i.includes(e));if(a.length>0){let r=new Set(i.map(({name:e})=>e)),o=a.some(({name:e})=>r.has(e));throw Error(`Listed in actions, but ${e}: ${JI(a,r)} (${t}${o?`; one marked (another contract) is a contract of that name ${n}`:``})`)}},XI=(e,t)=>t===void 0?e:(YI(qI.byImplementation,t,e.flatMap(e=>e.actions)),e.flatMap(e=>{let n=e.actions.filter(e=>t.includes(e));return n.length===0?[]:n.length===e.actions.length?[e]:[GI.share(n,e)]})),sfe=(e,t,n,r)=>{r!==void 0&&YI(qI.byBinding,r,t);let i=n.flatMap(e=>e.actions),a=XI(n,r??t.filter(e=>i.includes(e))),o=a.flatMap(e=>e.actions);if(o.length===0&&r===void 0&&n.length>0){let n=new Set(t.map(({name:e})=>e));throw Error(`No action of these implementations is in this ${e}: ${JI(i,n)||`none`} (pass an implementation of a bound action, or bind one of these)`)}return jI(`served action`,o,AI),a},cfe=(e,t,n,r)=>{let i=sfe(e,t.actions,KI(n),r.actions),a=i.flatMap(e=>e.actions);return bI(a,t.authentication),kI(`middleware`,r.middleware??[],e=>e.key,{fix:`list each middleware once`}),{apps:i,actions:a,authentication:a.some(e=>e.caller!==yI)?t.authentication:void 0}},ZI=e=>t=>{let[n,...r]=e.map(e=>GI.layerOf(e));return n===void 0?t:Cf(t,bf(n,...r))},QI=e=>V(qf(e,e=>GI.boundOf(e)),e=>e.flat()),lfe=(e,t,n)=>{let r={"action.name":e.name,"action.read_only":e.readOnly},i=e.caller===yI?L:B(Fp(e.caller),e=>Ni(e)?L:z(new CI)),a=e.caller===yI?L:Qf(()=>n(e)),o=Cx(Px(K(BI(e)))),s=(e,t)=>{let n=ta(e.annotations);return[hd(e.error).annotate(n),hd(_d(t)).annotate(n)]},c=H(function*(e){let t=[];for(let n of e.reasons)if(dd(n)){let e=yield*up(o(n.error));t.push(...Nd(e)?[n]:s(n,e.cause))}else t.push(n);return yield*tp(fd(t))});return n=>zp(i.pipe(sp(a),sp(Qf(()=>t(n))),hp(c))).pipe(_m(r),em(e.name,{attributes:r},{captureStackTrace:!1}))},$I={errors:`all`,onExcessProperty:`error`},eL=`effect-actions/media`,tL=W({data:CS,mimeType:U});tL.annotate({[eL]:`image`});const nL=e=>e.annotations?.[eL]===`image`,rL=e=>nL(e)&&e.encoding===void 0?`image`:void 0,ufe=Gx(U,Lx),iL=e=>jx(e)?e:Reflect.ownKeys(e).length===0?ufe:W(e);function aL(e,t){efe(e);let{caller:n,readOnly:r}=t;if(n!==yI&&!tte(n))throw Error(`Missing caller: declare Action.Anyone or an identity service key`);if(n!==yI&&ra(n))throw Error(`Invalid caller: an identity is a Context.Service, not a Context.Reference`);if(r!==!0&&r!==!1)throw Error(`Invalid readOnly: ${String(r)} (set true or false)`);let i={caller:n,name:e,description:t.description,input:iL(t.input??{}),success:t.success===void 0?Hx:iL(t.success),error:LI(t.error),readOnly:r,mcp:{...t.mcp}};return UI(`Action "${i.name}"`,BI(i)),i}const dfe=()=>L,oL=e=>{if(!$t(e))throw Error(`Missing authorize: not a function (pass your rule, Action.allowAll, or an Effect returning one)`);return e},ffe=e=>{if(e===void 0)throw Error(`Protected actions require authorize, or Action.allowAll`);return e},pfe=e=>{if(e!==void 0)throw Error(`A public-only target takes no authorize (remove it, or list a protected action)`);return dfe},mfe=e=>WI(Gf(e)?V(e,oL):F(oL(e)));function sL(e,t,n){let r=Aa(e),i=r.map(e=>e.name);jI(`action`,r);let a=mfe(r.some(e=>e.caller!==yI)?ffe(n?.authorize):pfe(n?.authorize)),o=t=>{let n=$t(t)?Object.fromEntries(Array.isArray(e)?[]:r.map(({name:e})=>[e,t])):t;tfe(`handlers`,Object.keys(n),i,`remove it, or list its action`);let a=r.flatMap(e=>{let t=Object.hasOwn(n,e.name)?n[e.name]:void 0;return $t(t)?[[e,t]]:[]}),o=i.filter(e=>!a.some(([t])=>t.name===e));if(o.length>0)throw Error(`Missing handlers: ${o.join(`, `)} (return the handler for one action, or a record with an own function per listed action)`);return a},s=Gf(t)?V(t,o):F(o(t));return new GI(r,WI(s),a)}const cL=e=>B(Pp(e[`~provider`]),t=>t.descriptor===e?F(t):rp(/* @__PURE__ */ Error(`Authentication "${e.name}": the descriptor named here is not the one its provider was built from (build both from one descriptor)`))),hfe=(e,t)=>B(Fp(e[`~verified`]),n=>Ni(n)?Lp(t,e.identity,n.value):z(new CI)),gfe={write(e){switch(e._tag){case`Event`:{let t=``;return e.id!==void 0&&(t+=`id: ${e.id}\n`),e.event!==`message`&&(t+=`event: ${e.event}\n`),t+=`data: ${e.data.replace(/\r\n|\r|\n/g,`
|
|
24
|
+
data: `)}\n`,t+`
|
|
25
|
+
`}case`Retry`:return`retry: ${_o(e.duration)}\n\n`}}};function lL(e){let t=typeof e==`string`?que(e):e;return e=>e.annotate({httpApiStatus:t})}const _fe=/*#__PURE__*/ (e=>Hx.pipe(lL(e)))(204),uL=e=>jx(e)&&N(e,`~effect/http-api/HttpApiSchema/Stream`),dL=e=>uL(e)&&e._tag===`StreamSse`,vfe=e=>uL(e)&&e._tag===`StreamUint8Array`,fL=`~effect/http-api/HttpApiSchema/WithHeaders`,yfe=e=>N(e,`~effect/http-api/HttpApiSchema/WithHeadersValue`),pL=e=>jx(e)&&N(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function bfe(e,t,n){return Ax(e.ast,{[fL]:fL,schema:t,headers:n})}function mL(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??hL(t._tag)}})}function hL(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function gL(e){return t=>mL(t,{_tag:`Json`,...e})}function _L(e){return t=>mL(t,{_tag:`FormUrlEncoded`,...e})}const vL=e=>{if(bv(e))return!0;let t=Jy(e);if(bv(t))return!0;let n=e.encoding?.[0].to;return n!==void 0&&bv(n)},yL=/*#__PURE__*/ ob(`~httpApiEncoding`),bL=/*#__PURE__*/ ob(`~httpApiWithHeaders`),xL=/*#__PURE__*/ ob(`httpApiStatus`),SL={_tag:`Json`,contentType:`application/json`},CL={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function wL(e){return yL(e)??SL}function TL(e,t){return yL(e)||(pA(t)?SL:CL)}function EL(e){let t=wL(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function DL(e){return xL(e)??200}function OL(e){return pL(e)?xL(e.ast)??DL(e.schema.ast):DL(e.ast)}function kL(e){return pL(e)&&yL(e.ast)===void 0?EL(e.schema.ast):EL(e.ast)}function AL(e){return xL(e)??500}function jL(e){return pL(e)?xL(e.ast)??AL(e.schema.ast):AL(e.ast)}function ML(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}const NL=`~effect/http-api/HttpApiEndpoint`;function PL(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function FL(e){let t=Array.from(e.success);return Ma(t)?t:[_fe]}function IL(e){let t=new Set(e.error),n=e.disableCodecs?M:GL;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}const LL={[NL]:NL,pipe(){return jt(this,arguments)},prefix(e){return zL({...RL(this),path:DM(this.path,e)})},middleware(e){return zL({...RL(this),middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},annotate(e,t){return zL({...RL(this),annotations:oa(this.annotations,e,t)})},annotateMerge(e){return zL({...RL(this),annotations:ha(this.annotations,e)})}},RL=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function zL(e){function t(){}return Object.setPrototypeOf(t,LL),Object.assign(t,e)}const BL=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?M:KS;return zL({identifier:t,path:n,method:e,params:VL(r?.params,a),query:VL(r?.query,a),headers:VL(r?.headers,a),payload:HL(r?.payload,e,i),success:WL(r?.success,e,i),error:KL(r?.error,i),annotations:ia(),middlewares:/* @__PURE__ */ new Set,disableCodecs:i})};function VL(e,t){if(e!==void 0)return jx(e)?t(e):t(W(e))}function HL(e,t,n){let r=/* @__PURE__ */ new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:jx(e)?[e]:[W(e).pipe(_L())],a=n?M:nR;for(let e of i){let n=TL(e.ast,t),i=ML(n.contentType),o=r.get(i);if(o){if(o.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(o.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);o.schemas.push(a(e,t))}else r.set(i,{encoding:n,schemas:[a(e,t)]})}return r}const UL=`effect/http-api/stream/failure`;function WL(e,t,n){if(e===void 0)return/* @__PURE__ */ new Set;let r=Aa(e);return qL(r,t),new Set(n?r:r.map(GL))}const GL=/*#__PURE__*/ Vt(e=>uL(e)?e:pL(e)?bfe(e,uL(e.schema)?e.schema:tR(e.schema,kL(e)),KS(e.headers)):eR(e));function KL(e,t){if(e===void 0)return/* @__PURE__ */ new Set;let n=Aa(e);for(let e of n){let t=pL(e)?e.schema:e;if(uL(t))throw Error(`Streaming schemas are not supported in error responses`)}return YL(n,jL),new Set(t?n:n.map(GL))}function qL(e,t){let n=!1,r=/* @__PURE__ */ new Map;for(let i of e){let e=pL(i)?i.schema:i,a=OL(i);if(uL(e)){if(XL(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=JL(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(ML(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);r.set(a,{...i,stream:e})}else{let t=JL(r,a),n=vL(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=kL(i);if(ML(e.contentType)===ML(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(ML(kL(i).contentType)),t.noContent=t.noContent||n}}YL(e,OL)}function JL(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:/* @__PURE__ */ new Set,noContent:!1},e.set(t,n)),n}function YL(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=bL(r.ast),a=pL(r)?r.schema:i?.body??r,o=vL(a.ast)?``:ML(uL(a)?a.contentType:kL(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:/* @__PURE__ */ new Set},n.set(e,s));let c=()=>/* @__PURE__ */ Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(pL(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function XL(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(dL(e)&&ZL(e.events.ast))throw Error(`SSE event name is reserved: ${UL}`)}function ZL(e){return QL(Jy(e),/* @__PURE__ */ new Set)}function QL(e,t){if(t.has(e))return!1;if(t.add(e),Tv(e))return e.types.some(e=>QL(e,t));if(Ev(e))return QL(e.thunk(),t);if(!wv(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&$L(n.type,t)}function $L(e,t){if(t.has(e))return!1;t.add(e);let n=Jy(e);return n===e?xv(e)?e.literal===UL:Tv(e)?e.types.some(e=>$L(e,t)):Ev(e)?$L(e.thunk(),t):!1:$L(n,t)}function eR(e){let t=EL(e.ast),n=bL(e.ast);return n===void 0?tR(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:tR(n.body,t),headersCodec:KS(n.headers)}})}function tR(e,t){switch(t._tag){case`Json`:return GS(e);case`FormUrlEncoded`:return KS(e);case`Text`:case`Uint8Array`:return e}}function nR(e,t){switch(TL(e.ast,t)._tag){case`Json`:return GS(e);case`FormUrlEncoded`:return KS(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}const rR=/*#__PURE__*/ BL(`POST`),iR=`~effect/http-api/HttpApi`,aR={[iR]:iR,pipe(){return jt(this,arguments)},add(...e){let t={...this.groups};for(let n of e)or(t,n.identifier,n);return sR({...oR(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];or(t,n,r.annotateMerge(ha(e.annotations,r.annotations)))}return sR({...oR(this),groups:t})},prefix(e){return sR({...oR(this),groups:Ea(this.groups,t=>t.prefix(e))})},middleware(e){return sR({...oR(this),groups:Ea(this.groups,t=>t.middleware(e))})},annotate(e,t){return sR({...oR(this),annotations:oa(this.annotations,e,t)})},annotateMerge(e){return sR({...oR(this),annotations:ha(this.annotations,e)})}},oR=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),sR=e=>{function t(){}return Object.setPrototypeOf(t,aR),Object.assign(t,e)},cR=e=>sR({identifier:e,groups:{},annotations:ia()}),lR=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=ha(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:ha(n,e.annotations),successes:uR(FL(e),OL),errors:uR(IL(e),jL)})}},uR=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach(r),n;function r(e){let r=pL(e)?e.schema:e;if(uL(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}};var dR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/AdditionalSchemas`)){},fR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParseOptions`)){},pR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParamsParseOptions`)){},mR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/QueryParseOptions`)){},hR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/HeadersParseOptions`)){},gR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/PayloadParseOptions`)){},_R=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/SuccessParseOptions`)){},vR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ErrorParseOptions`)){};const yR=e=>{let t=ca(e,fR);return{params:ca(e,pR)??t,query:ca(e,mR)??t,headers:ca(e,hR)??t,payload:ca(e,gR)??t,success:ca(e,_R)??t,error:ca(e,vR)??t}},bR=/*#__PURE__*/ aj({status:400}),xR=/*#__PURE__*/ aj({status:500}),SR=`~effect/http-api/HttpApiError/HttpApiSchemaError`;var CR=class e extends (/*#__PURE__*/ Io(`HttpApiSchemaError`)){[SR]=SR;get[aO](){return this.kind!==`Body`&&this.kind!==`ResponseHeaders`}static is(e){return N(e,SR)}static wrap(t,n){return bm(n,n=>new e({kind:t,cause:n}))}name=`HttpApiSchemaError`;message=this.kind;[Oj](){return F(this[`~effect/ErrorReporter/ignore`]?bR:xR)}};const wR=`~effect/http-api/HttpApiMiddleware`,TR=`~effect/http-api/HttpApiMiddleware/Security`,ER=e=>N(e,TR),DR=()=>(e,t)=>{let n=nr(),r;n!==0&&(rr(2),r=new globalThis.Error,rr(n));class i extends P()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[wR]=wR,a.error=OR(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[TR]=TR,a.security=t.security}return a};function OR(e){return e===void 0?/* @__PURE__ */ new Set:new Set(Array.isArray(e)?e:[e])}const kR=(e,t)=>uf(e,(e,n)=>pp(e,e=>CR.is(e)?t(e,n):z(e))),AR=/*#__PURE__*/ new Set;function jR(e){if(e===void 0)return AR;let t=My(e.ast);return wv(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function MR(e,t){if(t===void 0||!e.includes(`:`))return e;let n=jR(t);if(n===void 0)return e;let r=``,i=0,a=-1;for(let t=0;t<e.length;t++){let o=e[t];if(i>0||t===a){r+=o,o===`\\`?r+=e[++t]??``:o===`(`?i++:o===`)`&&i--;continue}if(o!==`:`){r+=o;continue}if(e[t+1]===`:`){r+=`::`,t++;continue}let s=/^:(\w+)/.exec(e.slice(t));if(s!==null&&n.has(s[1])){r+=s[0],t+=s[0].length-1;let n=e[t+1];n===`(`?a=t+1:n!==void 0&&!`/.-?`.includes(n)&&(r+=`(.*?)`)}else r+=`::`}return r}var NR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Identifier`)){},PR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Title`)){},FR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Version`)){},IR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Description`)){},LR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/License`)){},RR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/ExternalDocs`)){},zR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Servers`)){},BR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Format`)){},VR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Summary`)){},HR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Deprecated`)){},UR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Override`)){};const WR=/*#__PURE__*/ _a(`effect/http-api/OpenApi/Exclude`,{defaultValue:It});var GR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Transform`)){};const KR={},qR=/*#__PURE__*/ new WeakMap,JR=e=>{if(Array.isArray(e))return e.map(JR);if(typeof e==`object`&&e&&!Object.isFrozen(e)){let t={};for(let n of Object.keys(e))or(t,n,JR(e[n]));return t}return e};function YR(e,t,n){let r=ma(e,t);Ni(r)&&n(r.value)}function XR(e,t){let n=t??KR,r=qR.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,qR.set(n,r));let i=r.get(e);if(i!==void 0)return JR(i);let a=ZR(e,n);return r.set(e,JR(a)),a}function ZR(e,t){let n={openapi:`3.1.0`,info:{title:`Api`,version:`0.0.1`},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]},r=[],i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[];function s(e,t=`Json`){let n=t===`Text`?{type:`string`}:{};return r.push({_tag:`schema`,ast:sz(e,t),target:n}),n}YR(e.annotations,PR,e=>{n.info.title=e}),YR(e.annotations,FR,e=>{n.info.version=e}),YR(e.annotations,IR,e=>{n.info.description=e}),YR(e.annotations,LR,e=>{n.info.license=e}),YR(e.annotations,VR,e=>{n.info.summary=e}),YR(e.annotations,zR,e=>{n.servers=[...e]}),lR(e,{onGroup({group:e}){if(da(e.annotations,WR))return;let t={name:sa(e.annotations,PR,()=>e.identifier)};YR(e.annotations,IR,e=>{t.description=e}),YR(e.annotations,RR,e=>{t.externalDocs=e}),YR(e.annotations,UR,e=>{for(let[n,r]of Object.entries(e))or(t,n,r)}),YR(e.annotations,GR,e=>{t=e(t)}),n.tags.push(t)},onEndpoint({endpoint:e,group:t,mergedAnnotations:c,middleware:l}){if(da(c,WR))return;let u={tags:[sa(t.annotations,PR,()=>t.identifier)],operationId:sa(e.annotations,NR,()=>t.topLevel?e.identifier:`${t.identifier}.${e.identifier}`),parameters:[],security:[],responses:{}},d=jR(e.params),f=e.path.replace(/:(\w+)\??/g,(e,t)=>d===void 0||d.has(t)?`{${t}}`:e),p=e.method.toLowerCase(),m=p===`query`,h=m?`QUERY`:p;function g(e,t){for(let[n,{content:i,descriptions:a,headers:o,streamContent:c}]of e){let e=a.size>0?Array.from(a).join(` | `):t();or(u.responses,n,{description:e});for(let e of o)r.push({_tag:`properties`,ast:e.ast,select:e=>String(e.name).toLowerCase()!==`content-type`,apply(e,t){let r=String(e.name).toLowerCase();u.responses[n].headers??={},or(u.responses[n].headers,r,{schema:t,required:!e.isOptional})}});i!==void 0&&i.forEach((e,t)=>{e.forEach((e,r)=>{let i=Array.from(e,ay),a=i.length===1?i[0]:new hy(i);u.responses[n].content??={},or(u.responses[n].content,r,{schema:s(a,t)})})}),c!==void 0&&c.forEach((e,t)=>{u.responses[n].content??={},dL(e)?or(u.responses[n].content,t,{schema:s(e.events.ast),"x-effect-stream":{encoding:`sse`,causeSchema:s(ES(e.error,yS()).ast),errorSchema:s(e.error.ast),failureEvent:nz}}):or(u.responses[n].content,t,{schema:{type:`string`,format:`binary`},"x-effect-stream":{encoding:`uint8array`}})})}}function _(e,t){e&&r.push({_tag:`properties`,ast:e.ast,apply(e,n){u.parameters.push({name:String(e.name),in:t,schema:n,required:t===`path`||!e.isOptional})}})}YR(e.annotations,IR,e=>{u.description=e}),YR(e.annotations,VR,e=>{u.summary=e}),YR(e.annotations,HR,e=>{u.deprecated=e}),YR(e.annotations,RR,e=>{u.externalDocs=e}),l.forEach(e=>{if(ER(e))for(let[t,n]of Object.entries(e.security))v(t,n),u.security.push({[t]:[]})});function v(e,t){let r=lz(t);if(!Object.hasOwn(n.components.securitySchemes,e))or(n.components.securitySchemes,e,r);else if(!An(uz(n.components.securitySchemes[e]),uz(r)))throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${e}`)}let y=pA(e.method);if(y){let t=/* @__PURE__ */ new Map;for(let n of PL(e)){if(vL(n.ast))continue;let r=TL(n.ast,e.method),i=t.get(r.contentType);i===void 0?t.set(r.contentType,{encoding:r,schemas:[n]}):i.schemas.push(n)}if(t.size>0){let e={};for(let[n,{encoding:r,schemas:i}]of t){let t=i.map(ay);or(e,n,{schema:s(t.length===1?t[0]:new hy(t),r._tag)})}u.requestBody={content:e,required:!0}}}if(_(e.params,`path`),!y&&e.payload.size===1){let t=e.payload.values().next().value;_(t.schemas[0],`query`)}_(e.headers,`header`),_(e.query,`query`),g(rz(e),()=>`Success`),g(iz(IL(e),jL,az),()=>`Error`);let b=`${p} ${f.replace(/\{[^}]+\}/g,`{}`)}`;if(i.has(b))throw new globalThis.Error(`Duplicate OpenAPI operation for ${e.method} ${f}`);i.add(b),Object.hasOwn(n.paths,f)||or(n.paths,f,{});let x=()=>{let e=n.paths[f];return m?e[`x-oai-additionalOperations`]??={}:e};x()[h]=u,o.push(()=>{let t=x(),n=t[h];YR(e.annotations,UR,e=>{for(let[t,r]of Object.entries(e))or(n,t,r)}),YR(e.annotations,GR,e=>{n=e(n)});let r=n.operationId;if(r!==void 0){if(a.has(r))throw new globalThis.Error(`Duplicate OpenAPI operationId: ${r}`);a.add(r)}t[h]=n})}}),YR(e.annotations,dR,e=>{e.forEach(e=>{let t=sb(e.ast);if(t!==void 0){if(Object.hasOwn(n.components.schemas,t))throw new globalThis.Error(`Duplicate component schema identifier: ${t}`);or(n.components.schemas,t,s(e.ast))}})}),QR(r,t,n.components.schemas);for(let e of o)e();return Object.keys(n.components.schemas).forEach(e=>{if(!zb.test(e))throw new globalThis.Error(`Invalid component schema key: ${e}`)}),YR(e.annotations,UR,e=>{for(let[t,r]of Object.entries(e))or(n,t,r)}),YR(e.annotations,GR,e=>{n=e(n)}),n}function QR(e,t,n){if(!Ma(e))return;let r=dx(Ia(e,e=>e.ast),t),i=Ia(r.representations,(t,n)=>{let i=e[n];return i._tag===`schema`?t:$R(t,r.references,i.select)}),a=Kae(goe({representations:i,references:tz(i,r.references)},{onExcessProperty:`error`}));for(let t=0;t<e.length;t++){let n=e[t],r=a.schemas[t];if(n._tag===`schema`){sr(n.target,r);continue}let o=i[t];if(o._tag!==`Objects`)throw new globalThis.Error(`Expected an object representation for HTTP properties`);let s=r.properties;for(let e of o.propertySignatures)n.apply(e,s[String(e.name)])}for(let[e,t]of Object.entries(a.definitions))or(n,e,t)}function $R(e,t,n){let r=ez(e,t);return{_tag:`Objects`,propertySignatures:r._tag===`Objects`?r.propertySignatures.filter(e=>n?.(e)??!0).map(e=>({...e,name:String(e.name)})):[],indexSignatures:[],checks:[]}}function ez(e,t,n=/* @__PURE__ */ new Set){if(e._tag===`Suspend`)return ez(e.thunk,t,n);if(e._tag!==`Reference`||n.has(e.$ref))return e;let r=t[e.$ref];return r===void 0?e:ez(r,t,new Set(n).add(e.$ref))}function tz(e,t){let n={},r=/* @__PURE__ */ new WeakSet,i=[...e];function a(e){for(let t of e)t.representation?.schemas!==void 0&&i.push(...t.representation.schemas),t._tag===`FilterGroup`&&a(t.checks)}for(;i.length>0;){let e=i.pop();if(!r.has(e)){if(r.add(e),e._tag===`Reference`){if(Object.hasOwn(n,e.$ref))continue;let r=t[e.$ref];if(r===void 0)continue;or(n,e.$ref,r),i.push(r)}else switch(a(e.checks),e._tag){case`Declaration`:i.push(...e.typeParameters);break;case`Suspend`:i.push(e.thunk);break;case`TemplateLiteral`:i.push(...e.parts);break;case`Arrays`:for(let t of e.elements)i.push(t.type);i.push(...e.rest);break;case`Objects`:for(let t of e.propertySignatures)i.push(t.type);for(let t of e.indexSignatures)i.push(t.parameter,t.type);break;case`Union`:i.push(...e.types)}}}return n}const nz=`effect/http-api/stream/failure`;function rz(e){return iz(FL(e),OL,az)}function iz(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(i),r;function i(e){let i=bL(e.ast),c=pL(e)?e.schema:i?.body??e,l=pL(e)?e.headers:i?.headersCodec,u=t(e),d=c.ast;uL(c)?s(c,u):vL(d)?a(u,n(e.ast)??n(d)??`<No Content>`):o(c,u,kL(e),n(e.ast)??n(d)),l!==void 0&&r.get(u).headers.push(l)}function a(e,t){let n=r.get(e);n===void 0?r.set(e,{descriptions:/* @__PURE__ */ new Set([t]),content:void 0,headers:[],streamContent:void 0}):t!==void 0&&n.descriptions.add(t)}function o(e,t,n,i){let a=r.get(t),{_tag:o,contentType:s}=n;if(a===void 0)r.set(t,{descriptions:new Set(i===void 0?[]:[i]),content:/* @__PURE__ */ new Map([[o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]])]]),headers:[],streamContent:void 0});else if(i!==void 0&&a.descriptions.add(i),a.content===void 0)a.content=/* @__PURE__ */ new Map([[o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]])]]);else{let t=a.content.get(o);if(t===void 0)a.content.set(o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]]));else{let n=t.get(s);n===void 0?t.set(s,/* @__PURE__ */ new Set([e])):n.add(e)}}}function s(e,t){let n=r.get(t);n===void 0?r.set(t,{descriptions:/* @__PURE__ */ new Set,content:void 0,headers:[],streamContent:/* @__PURE__ */ new Map([[e.contentType,e]])}):n.streamContent===void 0?n.streamContent=/* @__PURE__ */ new Map([[e.contentType,e]]):n.streamContent.set(e.contentType,e)}}function az(e){return yae(e)??sb(e)}const oz=/*#__PURE__*/ U.annotate({format:`binary`});function sz(e,t){switch(t){case`Uint8Array`:return oz.ast;case`Text`:return yv(e)&&e.encoding===void 0?U.ast:e;case`Multipart`:e=cz(e)}return Gb(e)}function cz(e){return yv(e)&&e.annotations?.representation?.id===`effect/http/PersistedFile`?oz.ast:typeof e?.recur==`function`?e.recur(cz):e}const lz=e=>{let t={};switch(YR(e.annotations,IR,e=>{t.description=e}),e._tag){case`Basic`:return{...t,type:`http`,scheme:`basic`};case`Http`:{let n=ma(e.annotations,BR).pipe(Vi(e=>({bearerFormat:e})),zi);return{...t,type:`http`,scheme:e.scheme,...n}}case`ApiKey`:return{...t,type:`apiKey`,name:e.key,in:e.in}}},uz=e=>e.type===`http`?{...e,scheme:e.scheme.toLowerCase()}:e.in===`header`?{...e,name:e.name.toLowerCase()}:e,dz=(e,t)=>xM(H(function*(n){let r=yield*Ap(),i=[],a=Array.from(r.mapUnsafe.keys()).filter(e=>e.startsWith(`effect/http-api/HttpApiGroup/`)),o=Object.values(e.groups);for(let e of o){let t=r.mapUnsafe.get(e.key)?.routes;if(t===void 0){let t=a.length===0?`none`:a.join(`, `);return yield*rp(`HttpApiGroup "${e.identifier}" not found (key: "${e.key}"). Did you forget to provide HttpApiBuilder.group(api, "${e.identifier}", ...)? Available groups: ${t}`)}i.push(...t)}if(yield*n.addAll(i),t?.openapiPath){let r=Vt(e=>uj(XR(e)));yield*n.add(`GET`,t.openapiPath,I(()=>r(e)))}})),fz=(e,t,n)=>hf(R(function*(){let r=(yield*Ap()).pipe(ga(Kd)),i=e.groups[t],a=n(yz(i)),o=Gf(a)?yield*a:a,s=[];for(let t of o.handlers.values())s.push(Cz(e,i,t,r));return ta(/* @__PURE__ */ new Map([[i.key,{routes:s,handlers:o.handlers}]]))})),pz=`~effect/http-api/HttpApiBuilder/Handlers`,mz=e=>{switch(e._tag){case`Http`:return V(lM,t=>og(gz(t.headers.authorization,e.scheme)??``));case`ApiKey`:{let t=e.in===`header`?e.key.toLowerCase():e.key,n=W({[t]:U}),r=e.in===`query`?ele(n):e.in===`cookie`?Qce(n):$ce(n);return Dp(r,{onFailure:()=>og(``),onSuccess:e=>og(e[t])})}case`Basic`:{let e={username:``,password:og(``)};return V(lM,t=>{let n=gz(t.headers.authorization,hz);if(n===void 0)return e;let r=lte(bh(n));if(r===void 0)return e;let i=r.indexOf(`:`);return i===-1?e:{username:r.slice(0,i),password:og(r.slice(i+1))}})}}},hz=`Basic`;function gz(e,t){let n=t.length;if(e===void 0||e.length<=n||e.charCodeAt(n)!==32||e.slice(0,n).toLowerCase()!==t.toLowerCase())return;let r=n+1;for(;e.charCodeAt(r)===32;)r++;return r===e.length?void 0:e.slice(r)}const _z=(e,t,n,r,i)=>{if(!Object.hasOwn(e.group.endpoints,t))throw Error(`HttpApiEndpoint "${t}" not found in HttpApiGroup "${e.group.identifier}"`);if(e.handlers.has(t))throw Error(`Handler for HttpApiEndpoint "${t}" is already registered in HttpApiGroup "${e.group.identifier}"`);let a=e.group.endpoints[t];return e.handlers.set(t,{endpoint:a,handler:n,isRaw:r,uninterruptible:i?.uninterruptible??!1}),e},vz={[pz]:pz,pipe(){return jt(this,arguments)},handle(e,t,n){return _z(this,e,t,!1,n)},handleAll(e){for(let[t,n]of Object.entries(e)){let e=typeof n==`function`?n:n.handler,r=typeof n==`function`?void 0:n.options;_z(this,t,e,!1,r)}return this},handleRaw(e,t,n){return _z(this,e,t,!0,n)}},yz=e=>{let t=Object.create(vz);return t.group=e,t.handlers=/* @__PURE__ */ new Map,t};function bz(e,t){let n=/* @__PURE__ */ new Map;return e.forEach(({encoding:e,schemas:r},i)=>{let a=K(r),o=Cx(e._tag===`FormUrlEncoded`?qS(a):a,t);e._tag===`Multipart`?n.set(i,{_tag:`Multipart`,mode:e.mode,limits:e.limits,decode:o}):n.set(i,{_tag:e._tag,decode:o,nullOnEmpty:r.some(e=>Pie(Jy(e.ast)))})}),n}function xz(e,t,n){let r=pA(t.method),i=r?ML(t.headers[`content-type`]??`application/json`):`application/x-www-form-urlencoded`,a=e.get(i);if(!a)return lj(`Unsupported content-type: ${i}`,{status:415});let{_tag:o,decode:s}=a;switch(o){case`Multipart`:if(a.mode===`buffered`){let e=yp(t.multipart);return a.limits&&(e=Np(e,rM(a.limits))),B(e,s)}return F(a.limits?WE(t.multipartStream,rM(a.limits)):t.multipartStream);case`Json`:return B(yp(t.text),e=>{if(e===``)return s(a.nullOnEmpty?null:void 0);try{return s(JSON.parse(e))}catch{return z(new yx(new T_({message:`Expected a valid JSON body`})))}});case`Text`:return B(yp(t.text),s);case`FormUrlEncoded`:{let e=r?V(yp(t.urlParamsBody),Rg):F(n);return B(e,s)}case`Uint8Array`:return B(V(yp(t.arrayBuffer),e=>new Uint8Array(e)),s)}}function Sz(e,t,n,r,i,a){let o=ha(ha(e.annotations,t.annotations),n.annotations),s=yR(o),c=Ex(Uz(n,s.headers),s.success),l=Ex(Wz(n,s.headers),s.error),u=VO(n.params,e=>Cx(e,s.params)),d=VO(n.headers,e=>Cx(e,s.headers)),f=VO(n.query,e=>Cx(qS(e),s.query)),p=Mz(n,s.success),m=jz(n,s.success,s.headers),h=n.payload.size>0&&!a?bz(n.payload,s.payload):void 0;return wz(t,n,r,R(function*(){let e=QS().context,r=ua(e,lM),a=ua(e,bM),o=ua(e,uM),s={request:r,endpoint:n,group:t};if(u&&(s.params=yield*CR.wrap(`Params`,u(a.params))),d&&(s.headers=yield*CR.wrap(`Headers`,d(r.headers))),f&&(s.query=yield*CR.wrap(`Query`,f(o))),h){let e=xz(h,r,o);if(ij(e))return e;e!==void 0&&(s.payload=yield*CR.wrap(`Payload`,e))}let l=yield*i(s);if(ij(l))return l;let g;m!==void 0&&yfe(l)&&(g=l.headers,l=l.body);let _=yield*CR.wrap(`Body`,p?.(l,e)??(g===void 0?c(l):m.encodeBody(l)));if(m===void 0||g===void 0)return _;let v=yield*CR.wrap(`ResponseHeaders`,m.encodeHeaders.get(_.status)(g));return hj(_,v)})).pipe(aie,pp(e=>CR.is(e)?rp(e):yp(l(e))),Np(r))}function Cz(e,t,n,r){let i=n.endpoint;return TM(i.method,MR(i.path,i.params),Sz(e,t,i,r,n.handler,n.isRaw),{uninterruptible:n.uninterruptible})}const wz=(e,t,n,r)=>{let i={group:e,endpoint:t};for(let e of t.middlewares){let t=e,a=ua(n,t);r=(ER(t)?Ez(t,a):a)(r,i)}return r},Tz=/*#__PURE__*/ new WeakMap,Ez=(e,t)=>{let n=Tz.get(t);if(n!==void 0)return n;let r=Object.entries(e.security).map(([e,n])=>({decode:mz(n),middleware:t[e]}));if(r.length===0)return M;let i=H(function*(e,t){e=vp(e,e=>new Oz(e));let n;for(let i=0;i<r.length;i++){let{decode:a,middleware:o}=r[i],s=yield*lp(B(a,n=>o(e,{credential:n,endpoint:t.endpoint,group:t.group})));if(Ca(s)){if(kz(s.failure))return yield*z(s.failure.error);n=s}else return s.success}return yield*op(n)});return Tz.set(t,i),i},Dz=`~effect/http-api/HttpApiBuilder/HandlerError`;var Oz=class{[Dz]=Dz;error;constructor(e){this.error=e}};const kz=e=>N(e,Dz),Az=/*#__PURE__*/ vx(ij);function jz(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let t of e.success)pL(t)&&(r.set(OL(t),Ex(t.headers,n)),uL(t.schema)||i.push(Bz(t,n)));return r.size===0?void 0:{encodeBody:Ex(i.length===0?Lx:i.length===1?i[0]:K(i),t),encodeHeaders:r}}function Mz(e,t){let n=Nz(e);if(n===void 0)return;let r=n.body,i=Pz(e),a=OL(n.schema),o=r.contentType;if(vfe(r))return(e,t)=>pE(e)?F(fj(WE(e,t),{status:a,contentType:o})):i?void 0:new yx(new T_({message:`Expected a streaming response`}));let s=Fz(r,t);return(e,t)=>pE(e)?F(fj(WE(Iz(e,s),t),{status:a,contentType:o})):i?void 0:new yx(new T_({message:`Expected a streaming response`}))}function Nz(e){for(let t of e.success){let e=pL(t)?t.schema:t;if(uL(e))return{schema:t,body:e}}}function Pz(e){for(let t of e.success){let e=pL(t)?t.schema:t;if(jx(e)&&!uL(e))return!0}return e.success.size===0}function Fz(e,t){let n=GS(ES(e.error,yS()));return{sseMode:e.sseMode,encodeEvents:Ex(G(e.events),t),encodeCause:Ex(bS(n),t)}}function Iz(e,t){return e.pipe(t.sseMode===`data`?OE(e=>({id:void 0,event:`message`,data:e})):M,kE(e=>yp(t.encodeEvents(e))),PE(e=>hE(Lz(e,t))),OE(zz),VE)}function Lz(e,t){return t.encodeCause(e).pipe(yp,V(e=>({id:void 0,event:Rz,data:e})))}const Rz=`effect/http-api/stream/failure`;function zz(e){return gfe.write({_tag:`Event`,event:e.event,id:e.id,data:e.data})}const Bz=/*#__PURE__*/ Gz(OL),Vz=/*#__PURE__*/ Gz(jL);function Hz(e,t){return pL(e)?qz({schema:e,status:jL(e),encoding:kL(e),body:e.schema,headers:e.headers,headersOptions:t,toPair:e=>e}):Vz(e,t)}function Uz(e,t){let n=FL(e).map(e=>Bz(e,t));return n.length===1?n[0]:K(n)}function Wz(e,t){let n=IL(e).map(e=>Hz(e,t));return n.length===0?Lx:n.length===1?n[0]:K(n)}function Gz(e){let t=/* @__PURE__ */ new WeakMap;return(n,r)=>{let i=bL(n.ast);if(i!==void 0)return qz({schema:Px(n),status:e(i.body),encoding:EL(i.body.ast),body:i.bodyCodec,headers:i.headersCodec,headersOptions:r,toPair:i.transformation.encode});let a=pL(n)?n:n.ast,o=t.get(a);if(o!==void 0)return o;let s=pL(n)?n.schema:n,c=Az.pipe($x(s,Kz(e,n)));return t.set(a,c),c}}function Kz(e,t){let n=pL(t)?t.schema:t;return fv({decode:(e,t)=>z(new D_({message:`Encode only schema`},e,t)),encode:Jz(e(t),kL(t),vL(n.ast))})}function qz(e){let t=Ex(e.body),n=Ex(e.headers,e.headersOptions),r=Jz(e.status,e.encoding,vL(e.body.ast)),i=e=>e.issue,a=fv({decode:(e,t)=>z(new D_({message:`Encode only schema`},e,t)),encode:(a,o)=>{let s=e.toPair(a);return t(s.body,o).pipe(vp(i),B(e=>r(e,o)),B(e=>V(vp(n(s.headers),i),t=>hj(e,t))))}});return Az.pipe($x(e.schema,a))}function Jz(e,t,n){switch(t._tag){case`Json`:return(r,i)=>{if(r===void 0||n)return F(aj({status:e}));try{let n=JSON.stringify(r);return F(lj(n,{status:e,contentType:t.contentType}))}catch{return z(new T_({expected:`a JSON-serializable response body`},r,i))}};case`Text`:return n=>F(lj(n,{status:e,contentType:t.contentType}));case`Uint8Array`:return n=>F(sj(n,{status:e,contentType:t.contentType}));case`FormUrlEncoded`:return n=>F(nce(n,{status:e}).pipe(pj(`content-type`,t.contentType)))}}const Yz=`~effect/http-api/HttpApiGroup`,Xz={[Yz]:Yz,add(...e){let t={...this.endpoints};for(let n of e)or(t,n.identifier,n);return Qz({...Zz(this),endpoints:t})},prefix(e){return Qz({...Zz(this),endpoints:Ea(this.endpoints,t=>t.prefix(e))})},middleware(e){return Qz({...Zz(this),endpoints:Ea(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return Qz({...Zz(this),annotations:ha(this.annotations,e)})},annotate(e,t){return Qz({...Zz(this),annotations:oa(this.annotations,e,t)})},annotateEndpointsMerge(e){return Qz({...Zz(this),endpoints:Ea(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return Qz({...Zz(this),endpoints:Ea(this.endpoints,n=>n.annotate(e,t))})},pipe(){return jt(this,arguments)}},Zz=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),Qz=e=>{function t(){}return Object.setPrototypeOf(t,Xz),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},$z=(e,t)=>Qz({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ia()}),eB=`~effect/http-api/HttpApiSecurity`,tB={[eB]:eB,pipe(){return jt(this,arguments)}},nB=/*#__PURE__*/ (e=>Object.assign(Object.create(tB),{_tag:`Http`,scheme:e.scheme,schemeLength:e.scheme.length,annotations:ia()}))({scheme:`Bearer`}),rB=e=>Object.assign(Object.create(tB),{_tag:`ApiKey`,key:e.key,in:e.in??`header`,annotations:ia()}),iB=/* @__PURE__ */ new Set([`Body`,`ResponseHeaders`]);var aB=class extends DR()(`effect-actions/http/SchemaErrors`,{error:[SI]}){};const oB=()=>kR(aB,e=>z(iB.has(e.kind)?e:SI.fromSchemaError(e.cause))),sB=e=>(e??`/api`).split(`/`).filter(e=>e!==``),cB=e=>`/${e.join(`/`)}`,lB=e=>e.join(`/`)||`/`,uB=(e,t)=>{let n=$z(e,{topLevel:!0}),[r,...i]=t;return cR(`actions`).annotate(fR,{errors:`all`}).add(r===void 0?n:n.add(r,...i))},dB=(e,t,n)=>rR(e.name,t,{payload:e.input.pipe(gL()),success:e.success,error:n.map(II)}),fB=(e,t=[])=>t.reduce((e,t)=>e.middleware(t),e);function pB(e,t={}){let n=afe(`ActionHttp binding`,e,t),r=sB(t.prefix),i=n.authentication?.[`~middleware`],a=e.map(e=>{let t=i===void 0||e.caller===yI,a=dB(e,cB([...r,e.name]),VI(e,n)).annotate(IR,e.description);return t?a:a.middleware(i)}),o=uB(lB(r),a);return{actions:e,...n,prefix:cB(r),api:o}}const mB=e=>af((t,n)=>fie(lf(e,t,n),ia())),hB=()=>OM(V(Ap(),e=>{let t=ga(Kd)(e);return e=>Ip(e,e=>ha(t,e))})).layer;var gB=class extends DR()(`effect-actions/ActionHttp/StepUp`){},_B=class extends DR()(`effect-actions/ActionHttp/JsonContentType`){};const vB=()=>uf(_B,e=>B(lM,t=>t.headers[`content-type`]===void 0?F(lj(`Unsupported content-type: none`,{status:415})):e));function yB(e,t,n={}){let{apps:r,actions:i,authentication:a}=cfe(`HTTP binding`,e,t,n),o=sB(e.prefix),s=lB(o),c=uB(s,i.map(t=>{let r=fB(dB(t,cB([...o,t.name]),BI(t,e.error)).middleware(_B).middleware(aB),n.middleware);return t.caller===yI||a===void 0?r:r.middleware(gB).middleware(a[`~middleware`])})).annotate(gR,$I),l=vf(R(function*(){let e=yield*QI(r),t=a===void 0?ff:yield*V(cL(a),e=>bf(uf(a[`~middleware`],e.middleware),uf(gB,e.stepUp))),i=yield*qf(n.middleware??[],e=>V(Pp(e),t=>uf(e,t))),o=Object.fromEntries(e.map(([e,t])=>[e.name,e=>t(e.payload)]));return fz(c,s,e=>e.handleAll(o)).pipe(Cf([oB(),vB(),t,...i]),mB)})).pipe(ZI(r));return dz(c).pipe(Cf(l),Cf(hB()))}const bB=(e,t)=>uj(Ox(GS(e))(t),{status:PI(e.ast)??422}),xB=(e,t)=>{let n=zI(e).map(II).find(e=>Sx(e)(t));return n===void 0?void 0:bB(n,t)},SB=/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/,CB=(e,t)=>{let n=t.flatMap(([e,t])=>t===void 0?[]:[`${e}="${t.replace(/["\\]/g,`\\$&`)}"`]);return n.length===0?e:`${e} ${n.join(`, `)}`},wB=e=>CB(`Bearer`,e),TB=Sx(Qde),EB=(e,t)=>ln(e,`Forbidden`)&&e.scopes!==void 0?wB([[`error`,`insufficient_scope`],[`scope`,e.scopes.join(` `)],[`resource_metadata`,t],[`error_description`,SB.test(e.message)?e.message:void 0]]):void 0,DB={Unauthenticated:CI,Forbidden:TI},OB=e=>bB(DB[e._tag],e),kB=(e,t)=>{let n=OB(e),r=EB(e,t);return r===void 0?n:pj(n,`www-authenticate`,r)};var AB=class extends P()(`effect-actions/SteppedUp`){};const jB=e=>TB(e)&&(!ln(e,`Forbidden`)||e.scopes!==void 0),MB=e=>bp(e,e=>jB(e)?B(Fp(AB),t=>Ni(t)?BO(t.value,ji(e)):L):L),NB=(e,t)=>R(function*(){let n=yield*RO(Ai()),r=yield*up(Lp(e,AB,n)),i=yield*zO(n),a=Pd(r)&&(vd(r.cause)||yd(r.cause));return Ni(i)&&!a?kB(i.value,t):yield*r}),PB=/^[ \t]*Bearer +(.*[^ \t])[ \t]*$/i,FB=e=>Vi(Li(PB.exec(e??``)?.[1]),e=>og(e)),IB=e=>{let t=new URL(e.resource),n=new URL(t);return n.pathname=`/.well-known/oauth-protected-resource${t.pathname===`/`?``:t.pathname}`,n},LB=e=>({scope:e?.scopesRequired?.join(` `),metadataUrl:e===void 0?void 0:IB(e).href}),RB=e=>Ni(FB(e)),zB=(e,t)=>wB([[`error`,t?`invalid_token`:void 0],[`scope`,e.scope],[`resource_metadata`,e.metadataUrl]]),BB=(e,t)=>{if(t===void 0)return;if(!e)throw Error("A protected resource is published only for a Bearer scheme: drop `protectedResource`, or authenticate with a Bearer descriptor");if(Gf(t))return;for(let e of[`scopesSupported`,`scopesRequired`]){let n=t[e]?.find(e=>!wI.test(e));if(n!==void 0)throw Error(`Invalid scope in ${e}: "${n}", not an OAuth scope token: give each scope as its own element, of printable ASCII without a space, '"' or '\\'`)}let n=URL.parse(t.resource);if(n===null)throw Error(`A protected resource is an absolute URL: ${JSON.stringify(t.resource)} is not one; give the public URL of the endpoint clients connect to, such as https://api.example.com/mcp, read from configuration`);if(n.href.includes(`#`))throw Error(`A protected resource has no fragment: ${t.resource}; drop the "#", which no request URL carries, so its discovery would never answer`)},VB=(e,t)=>hj(e,{...e.headers[`cache-control`]===void 0?{"cache-control":`no-store`}:{},...t!==void 0&&e.status===401&&e.headers[`www-authenticate`]===void 0?{"www-authenticate":t}:{}}),HB=(e,t)=>{let n=t?.authentication,r=n===void 0||KB(n.security);BB(r,t?.protectedResource);let i=LB(t?.protectedResource),a=n!==void 0&&!r?JB(n.security,n.name):zB(i,RB(t?.authorization));if(!TB(e)){let t=xB(n?.error??[],e);if(t===void 0)throw Error("Not a refusal, nor an error the authentication declares: pass the descriptor declaring it as `authentication`, or answer the error yourself");return VB(t,a)}return VB(r?kB(e,i.metadataUrl):OB(e),a)},UB=/\.well-known|[\t\n\r]/,WB=e=>{let t=IB(e),n=t.href.slice(t.origin.length),r=uj({resource:e.resource,authorization_servers:e.authorizationServers,bearer_methods_supported:[`header`],scopes_supported:e.scopesSupported,resource_name:e.resourceName},{headers:{"access-control-allow-origin":`*`}}),i=e=>{let t=e.headers[`access-control-request-headers`];return aj({status:204,headers:{"access-control-allow-origin":`*`,"access-control-allow-methods":`GET, HEAD, OPTIONS`,...t===void 0?{}:{"access-control-allow-headers":t,vary:`Access-Control-Request-Headers`}}})};return e=>B(lM,a=>{let o=UB.test(a.url)&&URL.canParse(a.url,t.origin)&&new URL(a.url,t.origin).href.slice(t.origin.length)===n;return o&&(a.method===`GET`||a.method===`HEAD`)?F(r):o&&a.method===`OPTIONS`?F(i(a)):e})},GB=e=>{let t=LB(e);return{metadataUrl:t.metadataUrl,invalid:zB(t,!0),anonymous:zB(t,!1),published:e===void 0?void 0:WB(e)}},KB=e=>ln(e,`Http`)&&e.scheme.toLowerCase()===`bearer`,qB=/^[\w.-]+$/,JB=(e,t)=>EO(e).pipe(OO(`Http`,({scheme:e})=>CB(e,[])),OO(`Basic`,()=>CB(`Basic`,[[`realm`,t]])),OO(`ApiKey`,()=>void 0),FO),YB=(e,t,...n)=>{let r=n[0]?.security??nB,i=LI(n[0]?.error);if(!qB.test(e))throw Error(`Invalid authentication name: ${JSON.stringify(e)}, not an OpenAPI key: use only letters, digits, "_", "." and "-"`);if(UI(`Authentication "${e}"`,[...DI,...i]),!ln(r,`Http`)&&!ln(r,`ApiKey`)&&!ln(r,`Basic`))throw Error("Authentication takes one native HttpApiSecurity scheme as `security`: omit it for Bearer, or give one scheme, such as `HttpApiSecurity.basic`, never a record of them");return{name:e,identity:t,security:r,error:i,"~provider":P(`effect-actions/Authentication/Provider/${e}`),"~middleware":DR()(`effect-actions/Authentication/Security/${e}`,{security:{[e]:r}}),"~verified":P(`effect-actions/Authentication/Verified/${e}`)}},XB=e=>ag(e)?cg(e)!==``:e.username!==``||cg(e.password)!==``;function ZB(e,t,n={}){let{security:r}=e,i=KB(r),a=n.protectedResource;BB(i,a);let o=Gf(a)?V(a,e=>(BB(i,e),GB(e))):F(GB(a)),s=new CI({message:i?`A bearer token is required.`:`A credential is required.`});return pf(e[`~provider`],R(function*(){let{metadataUrl:n,invalid:a,anonymous:c,published:l}=yield*o;l!==void 0&&(yield*(yield*yM).addGlobalMiddleware(l));let u=Gf(t)?yield*t:t;if(!$t(u))return yield*rp(/* @__PURE__ */ Error(`Missing verify: pass a verify function, or an Effect building one`));let d=e=>XB(e)?u(e):z(s),f=ule((e,t)=>F(pj(t,`cache-control`,`no-store`))),p=t=>i?XB(t)?a:c:JB(r,e.name),m=t=>TB(t)?F(i?kB(t,n):OB(t)):Qf(()=>{let n=xB(e.error,t);return n===void 0?rp(t):F(n)}),h=(e,t,n)=>{let r=p(e);return kp(d(e),{onFailure:m,onSuccess:e=>Lp(t,n,e)}).pipe(Up(()=>f),dle((e,t)=>F(VB(t,r))))};return{descriptor:e,authenticate:d,middleware:{[e.name]:(t,{credential:n})=>h(n,t,e.identity)},stepUp:e=>i?_p(e,jB,e=>F(kB(e,n))):e,http:((t,a)=>B(mz(r),r=>a&&!XB(r)?t:h(r,i?NB(t,n):t,e[`~verified`]))),route:(t=>B(mz(r),n=>h(n,_p(t,TB,m),e.identity)))}}))}var QB=class e extends US()(`InternalServerError`,{message:U},{httpApiStatus:500}){cause;static of=t=>{let n=new e({message:`Request could not be completed`});return n.cause=t,n}},$B=class extends US()(`ServiceUnavailable`,{message:U},{httpApiStatus:503}){},eV=class e extends US()(`ClientNotFound`,{clientId:U,message:U},{httpApiStatus:404}){static of=t=>new e({clientId:t,message:`No client ${t} is registered`})},tV=class e extends US()(`ResourceNotFound`,{identifier:U,message:U},{httpApiStatus:404}){static of=t=>new e({identifier:t,message:`No resource ${t} exists`})},nV=class e extends US()(`ApiKeyNotFound`,{keyId:U,message:U},{httpApiStatus:404}){static of=t=>new e({keyId:t,message:`No API key ${t} exists`})},rV=class e extends US()(`ClientIsAutomatic`,{clientId:U,message:U},{httpApiStatus:409}){static of=t=>new e({clientId:t,message:`Client ${t} registered itself; revoke, block or delete it instead`})},iV=class e extends US()(`OwnerExists`,{message:U},{httpApiStatus:409}){static of=()=>new e({message:`Setup already completed`})},aV=class extends US()(`ProviderRefused`,{message:U},{httpApiStatus:400}){},oV=class extends US()(`UnreadableRequest`,{message:U},{httpApiStatus:400}){};const sV=[$B,QB];var cV=class extends P()(`clankerauth/CurrentOwner`){};const lV=e=>YB(`clankerauth.OwnerSession`,cV,{security:rB({in:`cookie`,key:e}),error:sV}),uV=lV(`better-auth.session_token`),dV=YB(`clankerauth.OwnerToken`,cV,{error:sV}),fV=e=>new URL(`/`,e).href,pV={read:`clankerauth:read`,write:`clankerauth:write`},mV=`Passwords have 8 to 128 characters`,hV=W({email:U.check(sS(/\S/u,{message:`Setup requires an email`})),password:U.check(fS(8,{message:mV}),mS(128,{message:mV}))}),gV=Xx([`none`,`client_secret_basic`,`client_secret_post`]),_V=Xx([`web`,`native`]),vV=G(U).check(gS({message:`Choose unique Resources`})),yV=W({client_name:U,redirect_uris:G(U),resources:vV,token_endpoint_auth_method:gV,application_type:_V}),bV=W({client_id:U,client_name:U,redirect_uris:G(U),application_type:_V}),xV=W({client_id:U}),SV=W({client_id:U,resource:Nx(U)}),CV=W({client_id:U,blocked:Vx}),wV=W({onboarding:Nx(Xx([`managed`,`dcr`,`cimd`])),blocked:Nx(Vx),client_id:U,client_name:Nx(U),redirect_uris:G(U),token_endpoint_auth_method:Nx(U),application_type:Nx(Zx(U)),scope:Nx(U),grant_types:Nx(G(U))}),TV=wV.pipe(Wx({client_secret:Nx(U),client_secret_expires_at:Nx(Bx)})),EV=W({identifier:U,name:U,scopes:G(U)}),DV=EV.pipe(Wx({builtIn:Vx})),OV=W({identifier:U,name:U.check(sS(/\S/u,{message:`Resources require a name`})),scopes:G(U.check(sS(/^\s*[\x21\x23-\x5B\x5D-\x7E]+\s*$/u,{message:`Resources require well-formed custom scopes`})))}),kV=W({identifier:U}),AV=W({resource:EV,created:Vx}),jV=W({client_id:U,resource:U}),MV=W({client_id:U,resources:vV}),NV=W({clientAccess:G(jV)}),PV=Gx(U,G(U)),FV=Gx(U,G(U).check(fS(1,{message:`Select explicitly granted, currently available Resource scopes`}),gS({message:`Select explicitly granted, currently available Resource scopes`}))).check(Joe(1,{message:`Select at least one Resource and scope`})),IV=U.check(mS(100,{message:`Key names require 1–100 characters`}),sS(/\S/u,{message:`Key names require 1–100 characters`})),LV=jS,RV=W({client_id:U,resource:U,scopes:G(U),approvedAt:Zx(LV),refreshedAt:Zx(LV)}),zV=W({name:IV,permissions:FV,expiresAt:Zx(LV)}),BV=W({keyId:U}),VV=W({keyId:U,name:Nx(IV),permissions:Nx(FV),enabled:Nx(Vx)}),HV=W({keyId:U,name:U,enabled:Vx,permissions:PV,expiresAt:Zx(LV),createdAt:LV}),UV={caller:yI},WV={caller:cV},GV=[aL(`setupStatus`,{description:`Check whether the issuer needs its first owner account.`,readOnly:!0,...UV,error:[QB],success:W({required:Vx})}),aL(`setupOwner`,{description:`Create the first owner account.`,readOnly:!1,...UV,error:[iV,aV,QB],input:hV,success:W({created:Vx}).pipe(lL(201))}),aL(`keyList`,{description:`The signed list a resource server verifies API keys against: one sealed entry per key granted on the resource, readable only with that key.`,readOnly:!0,...UV,error:[QB],input:W({resource:U}),success:W({list:U})})],KV=W({clients:G(wV),resources:G(DV),clientAccess:G(jV),connections:G(RV),email:U,issuer:U}),qV=[aL(`listClients`,{description:`List clients, resources, managed clients' resource access (what they may obtain), and every client's connections (what it holds).`,readOnly:!0,...WV,error:[QB],success:KV}),aL(`createClient`,{description:`Register a first-party OAuth client. Returns its secret once when confidential.`,readOnly:!1,...WV,error:[aV,QB],input:yV,success:TV.pipe(lL(201))}),aL(`updateClient`,{description:`Rename a first-party client or change its redirect URIs and application type.`,readOnly:!1,...WV,error:[eV,rV,aV,QB],input:bV,success:wV}),aL(`deleteClient`,{description:`Delete a client and its stored authorization. An automatic client can register again; block it to keep it out.`,readOnly:!1,...WV,error:[eV,QB],input:xV,success:W({deleted:Vx})}),aL(`revokeClient`,{description:`Revoke a client’s stored authorization, for one resource or all. It must authorize again; an automatic client asks for consent.`,readOnly:!1,...WV,error:[eV,QB],input:SV,success:W({revoked:Vx})}),aL(`blockClient`,{description:`Block or unblock OAuth authorization for a client.`,readOnly:!1,...WV,error:[eV,QB],input:CV,success:W({blocked:Vx})}),aL(`rotateClientSecret`,{description:`Rotate a confidential client secret. Returns the new secret once.`,readOnly:!1,...WV,error:[eV,rV,aV,QB],input:xV,success:TV}),aL(`setClientAccess`,{description:`Set the resources a managed client may obtain. Removing one revokes its authorization for it. Automatic clients may ask for any resource with consent.`,readOnly:!1,...WV,error:[eV,rV,QB],input:MV,success:NV}),aL(`getResource`,{description:`Get one resource and its scopes by identifier.`,readOnly:!0,...WV,error:[tV,QB],input:kV,success:DV}),aL(`putResource`,{description:`Create an OAuth resource, or update the one with its identifier, to exactly these name and scopes.`,readOnly:!1,...WV,error:[aV,QB],input:OV,success:AV}),aL(`deleteResource`,{description:`Delete a resource, its client access and every client’s authorization for it. API-key permissions are retained; recreating the resource restores them.`,readOnly:!1,...WV,error:[tV,QB],input:kV,success:W({deleted:Vx})}),aL(`listApiKeys`,{description:`List API key metadata without secret values.`,readOnly:!0,...WV,error:[QB],success:W({keys:G(HV)})}),aL(`createApiKey`,{description:`Create a scoped API key. Returns its secret once.`,readOnly:!1,...WV,error:[aV,QB],input:zV,success:HV.pipe(Wx({key:U}),lL(201))}),aL(`updateApiKey`,{description:`Update an API key’s name, permissions or enabled state.`,readOnly:!1,...WV,error:[nV,aV,QB],input:VV,success:HV}),aL(`deleteApiKey`,{description:`Delete an API key.`,readOnly:!1,...WV,error:[nV,QB],input:BV,success:W({deleted:Vx})})],JV=[.../* @__PURE__ */ new Set([...[...GV,...qV].flatMap(e=>e.error),...sV,oV])],YV=e=>pB([...qV,...GV],{authentication:e});YV(uV);const XV=pB(qV,{prefix:`/api/owner`,authentication:dV});var ZV=/* @__PURE__ */ e({NodeSqliteDialect:()=>rH}),QV=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},$V=class{#e;#t=new tH;#n;#r;constructor(e){this.#e={...e}}async init(){this.#n=this.#e.database,this.#r=new eH(this.#n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#r)}async acquireConnection(){return await this.#t.lock(),this.#r}async beginTransaction(e){await e.executeQuery(d.raw(`begin`))}async commitTransaction(e){await e.executeQuery(d.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(d.raw(`rollback`))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#n?.close()}},eH=class{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t),i=n;if(r.columns().length>0)return Promise.resolve({rows:r.all(...i)});let{changes:a,lastInsertRowid:o}=r.run(...i);return Promise.resolve({rows:[],numAffectedRows:BigInt(a),insertId:typeof o==`bigint`?o:BigInt(o)})}async*streamQuery(){throw Error(`Streaming query is not supported by SQLite driver.`)}},tH=class{#e;#t;async lock(){for(;this.#e!==void 0;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},nH=class extends r{getCurrentParameterPlaceholder(){return`?`}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}},rH=class{#e;constructor(e){this.#e={...e}}createDriver(){return new $V(this.#e)}createQueryCompiler(){return new nH}createAdapter(){return new QV}createIntrospector(e){return n(e)}};const iH=e=>{let t=Cx(e);return e=>vp(t(e),QB.of)};function aH(e){return(n,...r)=>Xf({try:async()=>(await t(n,...r).execute(e)).rows,catch:QB.of})}const oH=um(`Database.transaction`)(function*(e,t){let n=yield*Xf({try:()=>e.startTransaction().execute(),catch:QB.of}),r=yield*up(t(aH(n))),i=Sp(Xf({try:()=>n.rollback().execute(),catch:QB.of})),a=Xf({try:()=>n.commit().execute(),catch:QB.of}).pipe(bp(()=>i));return yield*Nd(r)?a:i,yield*r},Xp);async function sH(e){let n=new gee(e);try{n.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`);let e=new i({dialect:new rH({database:n})});return await t`SELECT 1`.execute(e),{kysely:e,sql:aH(e),close:()=>e.destroy()}}catch(e){throw n.close(),e}}var cH=class e extends P()(`clankerauth/Database`){static layer=t=>pf(e,R(function*(){yield*ip(()=>fee(ft(t),{recursive:!0,mode:448}));let e=yield*Bp(Xf(()=>sH(t)),e=>Yf(()=>e.close()));return{kysely:e.kysely,sql:e.sql,transaction:t=>oH(e.kysely,t)}}))};let lH,uH=!1;function dH(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function fH(){if(lH)return lH;let e=dH();if(e)return lH??=e,lH;try{let{AsyncLocalStorage:e}=await import(
|
|
26
|
+
/* @vite-ignore */
|
|
27
|
+
/* webpackIgnore: true */
|
|
28
|
+
`node:async_hooks`);return lH??=e,lH}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return lH??=t,lH;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(uH||(uH=!0,console.warn(`[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.`),console.warn(`[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler`),console.warn(`[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag`)),e)}}const pH=()=>b().context.endpointContextAsyncStorage,mH=async()=>{let e=pH();if(e)return e;let t=await fH(),n=b().context;return n.endpointContextAsyncStorage??=new t};function hH(){return ce()}function gH(){let e=hH();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function _H(e,t){return(await mH()).run(e,t)}const vH=async()=>{let e=b(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await fH();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function yH(){return(await vH()).getStore()!==void 0}async function bH(){let e=(await vH()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function xH(e,t){return(await vH()).run(e,t)}function SH(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await bH();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await bH()).set(t,e)}}}function CH(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}const Y=CH({USER_NOT_FOUND:`User not found`,FAILED_TO_CREATE_USER:`Failed to create user`,FAILED_TO_CREATE_SESSION:`Failed to create session`,FAILED_TO_UPDATE_USER:`Failed to update user`,FAILED_TO_GET_SESSION:`Failed to get session`,INVALID_PASSWORD:`Invalid password`,INVALID_EMAIL:`Invalid email`,INVALID_EMAIL_OR_PASSWORD:`Invalid email or password`,INVALID_USER:`Invalid user`,SOCIAL_ACCOUNT_ALREADY_LINKED:`Social account already linked`,PROVIDER_NOT_FOUND:`Provider not found`,INVALID_TOKEN:`Invalid token`,TOKEN_EXPIRED:`Token expired`,ID_TOKEN_NOT_SUPPORTED:`id_token not supported`,FAILED_TO_GET_USER_INFO:`Failed to get user info`,USER_EMAIL_NOT_FOUND:`User email not found`,EMAIL_NOT_VERIFIED:`Email not verified`,PASSWORD_TOO_SHORT:`Password too short`,PASSWORD_TOO_LONG:`Password too long`,USER_ALREADY_EXISTS:`User already exists.`,USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:`User already exists. Use another email.`,EMAIL_CAN_NOT_BE_UPDATED:`Email can not be updated`,CHANGE_EMAIL_DISABLED:`Change email is disabled`,CREDENTIAL_ACCOUNT_NOT_FOUND:`Credential account not found`,SESSION_EXPIRED:`Session expired. Re-authenticate to perform this action.`,FAILED_TO_UNLINK_LAST_ACCOUNT:`You can't unlink your last account`,ACCOUNT_NOT_FOUND:`Account not found`,USER_ALREADY_HAS_PASSWORD:`User already has a password. Provide that to delete the account.`,CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:`Cross-site navigation login blocked. This request appears to be a CSRF attack.`,VERIFICATION_EMAIL_NOT_ENABLED:`Verification email isn't enabled`,EMAIL_ALREADY_VERIFIED:`Email is already verified`,EMAIL_MISMATCH:`Email mismatch`,SESSION_NOT_FRESH:`Session is not fresh`,LINKED_ACCOUNT_ALREADY_EXISTS:`Linked account already exists`,INVALID_ORIGIN:`Invalid origin`,INVALID_CALLBACK_URL:`Invalid callbackURL`,INVALID_REDIRECT_URL:`Invalid redirectURL`,INVALID_ERROR_CALLBACK_URL:`Invalid errorCallbackURL`,INVALID_NEW_USER_CALLBACK_URL:`Invalid newUserCallbackURL`,MISSING_OR_NULL_ORIGIN:`Missing or null Origin`,CALLBACK_URL_REQUIRED:`callbackURL is required`,FAILED_TO_CREATE_VERIFICATION:`Unable to create verification`,FIELD_NOT_ALLOWED:`Field not allowed to be set`,ASYNC_VALIDATION_NOT_SUPPORTED:`Async validation is not supported`,VALIDATION_ERROR:`Validation Error`,MISSING_FIELD:`Field is required`,METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:`POST method requires deferSessionRefresh to be enabled in session config`,BODY_MUST_BE_AN_OBJECT:`Body must be an object`,PASSWORD_ALREADY_SET:`User already has a password set`}),wH=async()=>{let e=b(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await fH();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},TH=async e=>wH().then(t=>t.getStore()?.adapter||e).catch(()=>e),EH=async(e,t)=>{let n=!1;return wH().then(async r=>{n=!0;let i=[],a,o,s=!1;try{a=await r.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of i)await e();if(s)throw o;return a}).catch(e=>{if(!n)return t();throw e})},DH=async(e,t,n)=>{let r=!1;return wH().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=ot(e)?.();a&&await a;let o=[],s,c,l=!1;try{s=await e.transaction(async e=>(o=[],i.run({adapter:e,pendingHooks:o,isTransactionActive:!0},t)))}catch(e){l=!0,c=e}let u=async e=>{for(let t of o)try{await t()}catch(t){if(!n?.onAfterCommitHookError){if(e===`throw`)throw t;try{C.error(`Failed to run an after-commit hook for work that could not roll back`,t)}catch{}continue}try{await n.onAfterCommitHookError(t)}catch{}}};if(l)throw e.options?.adapterConfig.transaction===!1&&await u(`log`),c;return await u(`throw`),s}).catch(e=>{if(!r)return t();throw e})},OH=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await wH()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)};function kH(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function AH(e){let t=``;for(let n=0;n<e.length;n++)t+=kH(e[n]);return t}function jH(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${jH(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=AH(n),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let a=t?`${r}+?`:``,o=t?`${r}*?`:``,s=t?e.split(n):[e],c=``;for(let e=0;e<s.length;e++){let n=s[e],r=s[e+1],l=``;if(!(!n&&e>0)){if(t&&(l=e===s.length-1?o:r===`**`?``:a),t&&n===`**`)l&&(c+=e===0?``:l,c+=`(?:${i}*?${l})*?`);else{for(let e=0;e<n.length;e++){let t=n[e];t===`\\`?e<n.length-1&&(c+=kH(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:kH(t)}c+=l}}}return c}function MH(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function NH(e,t){if(typeof e!=`string`&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t==`string`||typeof t==`boolean`)&&(t={separator:t}),arguments.length===2&&!(t===void 0||typeof t==`object`&&t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t||={},t.separator===`\\`)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=jH(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=MH.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}function PH(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function FH(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}function IH(e){try{return(FH(new URL(e).pathname)||`/`)!==`/`}catch{throw new D(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function LH(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new D(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof D?t:new D(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function RH(e,t=`/api/auth`){if(LH(e),IH(e))return e;let n=FH(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function zH(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function BH(e,t,n,r,i){if(e)return RH(e,t);if(r!==!1){let e=S.BETTER_AUTH_URL||S.NEXT_PUBLIC_BETTER_AUTH_URL||S.PUBLIC_BETTER_AUTH_URL||S.NUXT_PUBLIC_BETTER_AUTH_URL||S.NUXT_PUBLIC_AUTH_URL||(S.BASE_URL===`/`?void 0:S.BASE_URL);if(e)return RH(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&zH(o,`proto`)&&zH(a,`host`))try{return RH(`${o}://${a}`,t)}catch{}if(n){let e=VH(n.url);if(!e)throw new D(`Could not get origin from request. Please provide a valid base URL.`);return RH(e,t)}if(typeof window<`u`&&window.location)return RH(window.location.origin,t)}function VH(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function HH(e){try{return new URL(e).protocol}catch{return null}}function UH(e){try{return new URL(e).host}catch{return null}}function WH(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function GH(e){if(e instanceof Request)return!0;if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Request]`)return!1;let t=e;return typeof t.url==`string`&&typeof t.headers==`object`&&t.headers!==null&&typeof t.headers.get==`function`}function KH(e,t){let n=GH(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&zH(e,`host`))return e}let r=n.get(`host`);if(r&&zH(r,`host`))return r;if(GH(e))try{return new URL(e.url).host}catch{return null}return null}function qH(e,t,n){if(t===`http`||t===`https`)return t;let r=GH(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&zH(e,`proto`))return e}if(GH(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=KH(e,n);return i&&PH(i)?`http`:`https`}const JH=(e,t)=>{if(!e||!t)return!1;let n=e.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase(),r=t.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase();return r.includes(`*`)||r.includes(`?`)?NH(r)(n):n.toLowerCase()===r.toLowerCase()};function YH(e,t,n,r){let i=KH(t,r);if(!i){if(e.fallback)return RH(e.fallback,n);throw new D(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>JH(i,e)))return RH(`${qH(t,e.protocol,r)}://${i}`,n);if(e.fallback)return RH(e.fallback,n);throw new D(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(`, `)}. Add this host to your allowedHosts config or provide a fallback URL.`)}function XH(e,t,n,r,i){if(WH(e))return n?YH(e,n,t,i):e.fallback?RH(e.fallback,t):BH(void 0,t,void 0,r,i);let a=GH(n)?n:void 0;return BH(typeof e==`string`?e:void 0,t,a,r,i)}const ZH=f(`a-z`,`0-9`,`A-Z`,`-_`);var QH=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(de(e),Te(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Ee(r)}update(e){return Oe(this),this.iHash.update(e),this}digestInto(e){Oe(this),T(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const $H=/* @__PURE__ */ (()=>{let e=((e,t,n)=>new QH(e,t).update(n).digest());return e.create=(e,t)=>new QH(e,t),e})(),eU=/* @__PURE__ */ Uint8Array.of(0),tU=/* @__PURE__ */ Uint8Array.of();function nU(e,t,n,r=32,i){de(e),De(r,`length`),Te(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=tU:Te(n,void 0,`info`),!o)return i&&Ee(t),/* @__PURE__ */ new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=$H.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){eU[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(eU).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(eU[0]=o,o>1&&c.update(u),c.update(n).update(eU).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&Ee(u),Ee(eU),r===s.length)return s;let f=s.slice(0,r);return Ee(s),f}const rU=(e,t,n,r,i)=>{de(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=$H.create(e,n).update(t);return nU(e,a.digest(),r,i,a)},iU=e=>e/2**32|0,aU=e=>e>>>0;function oU(e,t,n,r){let i=iU(n),a=aU(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function sU(e,t,n){return e&t^~e&n}function cU(e,t,n){return e&t^e&n^t&n}var lU=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=g(this.buffer)}update(e){Oe(this),Te(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=g(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){Oe(this),T(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),oU(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:g(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const uU=/* @__PURE__ */ Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),dU=/* @__PURE__ */ Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fU=/* @__PURE__ */ new Uint32Array(64);var pU=class extends lU{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)fU[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=fU[e-15],n=fU[e-2],r=te(t,7)^te(t,18)^t>>>3,i=te(n,17)^te(n,19)^n>>>10;fU[e]=i+fU[e-7]+r+fU[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=te(o,6)^te(o,11)^te(o,25),u=l+t+sU(o,s,c)+dU[e]+fU[e]|0,d=(te(n,2)^te(n,13)^te(n,22))+cU(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Ee(fU)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ee(this.buffer)}},mU=class extends pU{constructor(){super(32,uU)}};const hU=/* @__PURE__ */ re(()=>new mU,/* @__PURE__ */ h(1));async function gU(e,t,n=3600){return await new tI(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function _U(e,t){try{return(await $F(e,new TextEncoder().encode(t))).payload}catch{return null}}const vU=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),yU=()=>Date.now()/1e3|0,bU=`A256CBC-HS512`;function xU(e,t){return rU(hU,new TextEncoder().encode(e),new TextEncoder().encode(t),vU,64)}function SU(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function CU(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function wU(e,t,n,r=3600){let i=xU(SU(t),n),a=await oI({kty:`oct`,k:mP(i)},`sha256`);return await new Ide(e).setProtectedHeader({alg:`dir`,enc:bU,kid:a}).setIssuedAt().setExpirationTime(yU()+r).setJti(crypto.randomUUID()).encrypt(i)}const TU={clockTolerance:15,keyManagementAlgorithms:[`dir`],contentEncryptionAlgorithms:[bU,`A256GCM`]};async function EU(e,t,n){if(!e)return null;let r=!1;try{r=pI(e).kid!==void 0}catch{return null}try{let r=CU(t),{payload:i}=await eI(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=xU(e.value,n);if(t===await oI({kty:`oct`,k:mP(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,xU(r[0].value,n)},TU);return i}catch{if(r)return null;let i=CU(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await eI(e,xU(r.value,n),TU);return a}catch{continue}return null}}function DU(e,t){typeof e==`string`&&(e=new TextEncoder().encode(e)),typeof t==`string`&&(t=new TextEncoder().encode(t));let n=new Uint8Array(e),r=new Uint8Array(t),i=n.length^r.length,a=Math.max(n.length,r.length);for(let e=0;e<a;e++)i|=(e<n.length?n[e]:0)^(e<r.length?r[e]:0);return i===0}const OU={N:16384,r:16,p:1,dkLen:64};function kU(e,t){return new Promise((n,r)=>{lt(e.normalize(`NFKC`),t,OU.dkLen,{N:OU.N,r:OU.r,p:OU.p,maxmem:128*OU.N*OU.r*2},(e,t)=>{e?r(e):n(t)})})}async function AU(e){let t=ct(16).toString(`hex`);return`${t}:${(await kU(e,t)).toString(`hex`)}`}async function jU(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await kU(t,n)).toString(`hex`)===r}const MU=AU,NU=async({hash:e,password:t})=>jU(e,t);function PU(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function FU(e,t){return{digest:async n=>{let r=le(n),i=await PU().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?me.encode(i,{padding:t!==`base64urlnopad`}):he.encode(i):i}}}
|
|
29
|
+
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
30
|
+
function IU(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const LU=e=>e?`"${e}" `:``;function RU(e,t=``){if(typeof e!=`boolean`)throw TypeError(LU(t)+`expected boolean, got type=`+typeof e);return e}function zU(e,t=``){if(typeof e!=`number`)throw TypeError(LU(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(LU(t)+`expected integer >= 0, got `+e);return e}function BU(e,t,n=``){if(IU(e)&&(t===void 0||e.length===t))return e;t!==void 0&&zU(t,`length`);let r=IU(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=LU(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const VU=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function HU(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function UU(e,t){BU(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function WU(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function GU(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function KU(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const qU=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function JU(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function YU(e){for(let t=0;t<e.length;t++)e[t]=JU(e[t]);return e}const XU=qU?e=>e:YU,ZU=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,QU=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function $U(e){if(BU(e),ZU)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=QU[e[n]];return t}function eW(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function tW(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(ZU)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=eW(e.charCodeAt(i)),a=eW(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function nW(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function rW(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function iW(e,t){if(rW(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function aW(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];BU(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function oW(e,t){return VU(e,`defaults`),VU(t,`opts`),Object.assign(e,t)}function sW(e,t){if(e=BU(e),t=BU(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function cW(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(/* @__PURE__ */ new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}const lW=(e,t)=>{function n(n,...r){if(BU(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];BU(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(IU(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&BU(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);BU(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,BU(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(BU(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function uW(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(BU(t,e,`output`),n&&!fW(t))throw Error(`invalid output, must be aligned`);return t}function dW(e,t,n){zU(e),zU(t),RU(n);let r=/* @__PURE__ */ new Uint8Array(16),i=KU(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function fW(e){return e.byteOffset%4==0}function pW(e){return Uint8Array.from(BU(e))}function mW(e=32){zU(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function hW(e,t=mW){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;zU(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=aW(e,t);return rW(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){BU(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){BU(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}const gW=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),_W=/* @__PURE__ */ XU(WU(gW(`expand 16-byte k`))),vW=/* @__PURE__ */ XU(WU(gW(`expand 32-byte k`)));function yW(e,t){return e<<t|e>>>32-t}const bW=2**32-1,xW=/* @__PURE__ */ Uint32Array.of();function SW(e,t,n,r,i,a,o,s){let c=i.length,l=/* @__PURE__ */ new Uint8Array(64),u=WU(l),d=qU&&fW(i)&&fW(a),f=d?WU(i):xW,p=d?WU(a):xW;if(qU)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=bW)throw Error(`arx: counter overflow`);let h=Math.min(64,c-m);if(d&&h===64){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<16;t++)n=e+t,p[n]=f[n]^u[t];m+=64}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),XU(u),o>=bW)throw Error(`arx: counter overflow`);let f=Math.min(64,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function CW(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=oW({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return zU(i),zU(o),RU(a),RU(n),(t,s,c,l,u=0)=>{BU(t,void 0,`key`),BU(s,void 0,`nonce`),BU(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=uW(d,l,!1),f&&iW(c,l),zU(u),u<0||u>=bW)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=pW(t)),g=vW;else if(m===16&&n)h=/* @__PURE__ */ new Uint8Array(32),h.set(t),h.set(t,16),g=_W,p.push(h);else throw BU(t,32,`arx key`),Error(`invalid key size`);(!qU||!fW(s))&&p.push(s=pW(s));let _=WU(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(qU)r(g,_,WU(e),_);else{let t=XU(Uint32Array.from(g));r(t,_,WU(e),_),GU(t),XU(_)}s=s.subarray(16)}else qU||XU(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=/* @__PURE__ */ new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=XU(WU(s));try{return SW(e,g,_,y,c,l,u,o),l}finally{GU(...p)}}}function wW(e,t){return e[t++]&255|(e[t++]&255)<<8}var TW=class{blockLen=16;outputLen=16;buffer=/* @__PURE__ */ new Uint8Array(16);r=/* @__PURE__ */ new Uint16Array(10);h=/* @__PURE__ */ new Uint16Array(10);pad=/* @__PURE__ */ new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=pW(BU(e,32,`key`));let t=wW(e,0),n=wW(e,2),r=wW(e,4),i=wW(e,6),a=wW(e,8),o=wW(e,10),s=wW(e,12),c=wW(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=wW(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=wW(e,t+0),_=wW(e,t+2),v=wW(e,t+4),y=wW(e,t+6),b=wW(e,t+8),x=wW(e,t+10),S=wW(e,t+12),ee=wW(e,t+14),C=i[0]+(g&8191),te=i[1]+((g>>>13|_<<3)&8191),w=i[2]+((_>>>10|v<<6)&8191),ne=i[3]+((v>>>7|y<<9)&8191),T=i[4]+((y>>>4|b<<12)&8191),re=i[5]+(b>>>1&8191),ie=i[6]+((b>>>14|x<<2)&8191),ae=i[7]+((x>>>11|S<<5)&8191),oe=i[8]+((S>>>8|ee<<8)&8191),se=i[9]+(ee>>>5|r),ce=0,le=ce+C*o+5*h*te+5*m*w+5*p*ne+5*f*T;ce=le>>>13,le&=8191,le+=5*d*re+5*u*ie+5*l*ae+5*c*oe+5*s*se,ce+=le>>>13,le&=8191;let ue=ce+C*s+te*o+5*h*w+5*m*ne+5*p*T;ce=ue>>>13,ue&=8191,ue+=5*f*re+5*d*ie+5*u*ae+5*l*oe+5*c*se,ce+=ue>>>13,ue&=8191;let de=ce+C*c+te*s+w*o+5*h*ne+5*m*T;ce=de>>>13,de&=8191,de+=5*p*re+5*f*ie+5*d*ae+5*u*oe+5*l*se,ce+=de>>>13,de&=8191;let fe=ce+C*l+te*c+w*s+ne*o+5*h*T;ce=fe>>>13,fe&=8191,fe+=5*m*re+5*p*ie+5*f*ae+5*d*oe+5*u*se,ce+=fe>>>13,fe&=8191;let pe=ce+C*u+te*l+w*c+ne*s+T*o;ce=pe>>>13,pe&=8191,pe+=5*h*re+5*m*ie+5*p*ae+5*f*oe+5*d*se,ce+=pe>>>13,pe&=8191;let me=ce+C*d+te*u+w*l+ne*c+T*s;ce=me>>>13,me&=8191,me+=re*o+5*h*ie+5*m*ae+5*p*oe+5*f*se,ce+=me>>>13,me&=8191;let he=ce+C*f+te*d+w*u+ne*l+T*c;ce=he>>>13,he&=8191,he+=re*s+ie*o+5*h*ae+5*m*oe+5*p*se,ce+=he>>>13,he&=8191;let ge=ce+C*p+te*f+w*d+ne*u+T*l;ce=ge>>>13,ge&=8191,ge+=re*c+ie*s+ae*o+5*h*oe+5*m*se,ce+=ge>>>13,ge&=8191;let _e=ce+C*m+te*p+w*f+ne*d+T*u;ce=_e>>>13,_e&=8191,_e+=re*l+ie*c+ae*s+oe*o+5*h*se,ce+=_e>>>13,_e&=8191;let ve=ce+C*h+te*m+w*p+ne*f+T*d;ce=ve>>>13,ve&=8191,ve+=re*u+ie*l+ae*c+oe*s+se*o,ce+=ve>>>13,ve&=8191,ce=(ce<<2)+ce|0,ce=ce+le|0,le=ce&8191,ce>>>=13,ue+=ce,i[0]=le,i[1]=ue,i[2]=de,i[3]=fe,i[4]=pe,i[5]=me,i[6]=he,i[7]=ge,i[8]=_e,i[9]=ve}finalize(){let{h:e,pad:t}=this,n=/* @__PURE__ */ new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;GU(n)}update(e){HU(this),BU(e),e=pW(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,GU(this.h,this.r,this.buffer,this.pad)}digestInto(e){HU(this),UU(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};const EW=/* @__PURE__ */ cW(32,e=>new TW(e));function DW(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,ee=s,C=c,te=l,w=u,ne=d,T=f,re=p,ie=m,ae=h,oe=g,se=_,ce=v,le=y,ue=b,de=x;for(let e=0;e<a;e+=2)S=S+w|0,ce=yW(ce^S,16),ie=ie+ce|0,w=yW(w^ie,12),S=S+w|0,ce=yW(ce^S,8),ie=ie+ce|0,w=yW(w^ie,7),ee=ee+ne|0,le=yW(le^ee,16),ae=ae+le|0,ne=yW(ne^ae,12),ee=ee+ne|0,le=yW(le^ee,8),ae=ae+le|0,ne=yW(ne^ae,7),C=C+T|0,ue=yW(ue^C,16),oe=oe+ue|0,T=yW(T^oe,12),C=C+T|0,ue=yW(ue^C,8),oe=oe+ue|0,T=yW(T^oe,7),te=te+re|0,de=yW(de^te,16),se=se+de|0,re=yW(re^se,12),te=te+re|0,de=yW(de^te,8),se=se+de|0,re=yW(re^se,7),S=S+ne|0,de=yW(de^S,16),oe=oe+de|0,ne=yW(ne^oe,12),S=S+ne|0,de=yW(de^S,8),oe=oe+de|0,ne=yW(ne^oe,7),ee=ee+T|0,ce=yW(ce^ee,16),se=se+ce|0,T=yW(T^se,12),ee=ee+T|0,ce=yW(ce^ee,8),se=se+ce|0,T=yW(T^se,7),C=C+re|0,le=yW(le^C,16),ie=ie+le|0,re=yW(re^ie,12),C=C+re|0,le=yW(le^C,8),ie=ie+le|0,re=yW(re^ie,7),te=te+w|0,ue=yW(ue^te,16),ae=ae+ue|0,w=yW(w^ae,12),te=te+w|0,ue=yW(ue^te,8),ae=ae+ue|0,w=yW(w^ae,7);let fe=0;r[fe++]=o+S|0,r[fe++]=s+ee|0,r[fe++]=c+C|0,r[fe++]=l+te|0,r[fe++]=u+w|0,r[fe++]=d+ne|0,r[fe++]=f+T|0,r[fe++]=p+re|0,r[fe++]=m+ie|0,r[fe++]=h+ae|0,r[fe++]=g+oe|0,r[fe++]=_+se|0,r[fe++]=v+ce|0,r[fe++]=y+le|0,r[fe++]=b+ue|0,r[fe++]=x+de|0}function OW(e,t,n,r){let i=qU?e:XU(e.slice(0,4)),a=qU?t:XU(t.slice(0,8)),o=qU?n:XU(n.slice(0,4)),s=/* @__PURE__ */ new Uint32Array(16);DW(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,XU(r),qU||GU(i,a,o),GU(s)}const kW=/* @__PURE__ */ CW(DW,{counterRight:!1,counterLength:8,extendNonceFn:OW,allowShortKeys:!1}),AW=/* @__PURE__ */ new Uint8Array(16),jW=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(AW.subarray(n))},MW=/* @__PURE__ */ new Uint8Array(32);function NW(e,t,n,r,i){i!==void 0&&BU(i,void 0,`AAD`);let a=e(t,n,MW),o=dW(r.length,i?i.length:0,!0),s=EW.create(a);i&&jW(s,i),jW(s,r),s.update(o);let c=s.digest();return GU(a,o),c}const PW=/* @__PURE__ */ lW({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},/* @__PURE__ */ (e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=uW(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=NW(e,t,n,s,r);return a.set(c,o),GU(c),a},decrypt(i,a){a=uW(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=NW(e,t,n,o,r);if(!sW(s,c))throw GU(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),GU(c),a}}))(kW)),FW={name:`HMAC`,hash:`SHA-256`},IW=`$ba$`;function LW(e){if(!e.startsWith(IW))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function RW(e,t){return`${IW}${e}$${t}`}async function zW(e,t){let n=await FU(`SHA-256`).digest(e),r=nW(t);return $U(hW(PW)(new Uint8Array(n)).encrypt(r))}async function BW(e,t){let n=await FU(`SHA-256`).digest(e),r=tW(t),i=hW(PW)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}const VW=async({key:e,data:t})=>{if(typeof e==`string`)return zW(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await zW(n,t);return RW(e.currentVersion,r)},HW=async({key:e,data:t})=>{if(typeof e==`string`)return BW(e,t);let n=LW(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return BW(t,n.ciphertext)}if(e.legacySecret)return BW(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},UW=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await PU().importKey(`raw`,t,FW,!1,[`sign`,`verify`])},WW=async(e,t)=>{let n=await UW(t),r=await PU().sign(FW.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))};function GW(e){return!!e.database||!!e.secondaryStorage}function KW(e){return!!e.database}function qW(e){return KW(e)}function JW(e){return Ie(Re,e)}function YW(e){return je(Xe,e)}function XW(e){return Me(tt,e)}const ZW=A({id:k(),createdAt:nt().default(()=>/* @__PURE__ */ new Date),updatedAt:nt().default(()=>/* @__PURE__ */ new Date)}),QW=ZW.extend({userId:JW(),expiresAt:nt(),token:k(),ipAddress:k().nullish(),userAgent:k().nullish()}),$W=ZW.extend({email:k().transform(e=>e.toLowerCase()),emailVerified:Je().default(!1),name:k(),image:k().nullish()});function eG(e,t){if(!e||!t)return e;let n=Object.entries(t).filter(([,{returned:e}])=>e===!1).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!n.includes(e)).reduce((e,[t,n])=>({...e,[t]:n}),{})}const tG=/* @__PURE__ */ new WeakMap;function nG(e,t,n){let r=`${t}:${n}`;tG.has(e)||tG.set(e,/* @__PURE__ */ new Map);let i=tG.get(e);if(i.has(r))return i.get(r);let a=n===`output`?ie(e)[t]?.fields??{}:{},o=t===`user`||t===`session`||t===`account`?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(s={...s,...n.schema[t].fields});return i.set(r,s),s}function rG(e,t){return eG(t,nG(e,`user`,`output`))}function iG(e,t){let n=nG(e,`user`,`output`),r={};for(let e in n){let i=n[e];i.returned!==!1&&(e in t&&t[e]!==void 0?r[e]=t[e]:i.defaultValue===void 0?i.required||(r[e]=null):r[e]=typeof i.defaultValue==`function`?i.defaultValue():i.defaultValue)}return`id`in t&&(r.id=t.id),r}function aG(e,t){return eG(t,nG(e,`session`,`output`))}function oG(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=eG(t,nG(e,`account`,`output`));return c}function sG(e,t){let n=t.action||`create`,r=t.fields,i=Object.create(null);for(let t in r)if(t in e){if(r[t].input===!1){if(r[t].defaultValue!==void 0&&n!==`update`){i[t]=r[t].defaultValue;continue}if(e[t])throw E.from(`BAD_REQUEST`,{...Y.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(r[t].validator?.input&&e[t]!==void 0){let n=r[t].validator.input[`~standard`].validate(e[t]);if(n instanceof Promise)throw E.from(`INTERNAL_SERVER_ERROR`,Y.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw E.from(`BAD_REQUEST`,{...Y.VALIDATION_ERROR,message:n.issues[0]?.message||`Validation Error`});i[t]=n.value;continue}if(r[t].transform?.input&&e[t]!==void 0){i[t]=r[t].transform?.input(e[t]);continue}i[t]=e[t]}else if(r[t].defaultValue!==void 0&&n===`create`){if(typeof r[t].defaultValue==`function`){i[t]=r[t].defaultValue();continue}i[t]=r[t].defaultValue}else if(r[t].required&&n===`create`)throw E.from(`BAD_REQUEST`,{...Y.MISSING_FIELD,message:`${t} is required`});return i}function cG(e,t={},n){return sG(t,{fields:nG(e,`user`,`input`),action:n})}function lG(e,t={},n){let r=nG(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return sG(i,{fields:r,action:n})}function uG(e,t,n){return sG(t,{fields:nG(e,`session`,`input`),action:n})}function dG(e){let t=nG(e,`session`,`input`),n={};for(let e in t)t[e].defaultValue!==void 0&&(n[e]=typeof t[e].defaultValue==`function`?t[e].defaultValue():t[e].defaultValue);return n}function fG(e,t){if(!t)return e;for(let n in t){let r=t[n]?.modelName;r&&(e[n].modelName=r);for(let r in e[n].fields){let i=t[n]?.fields?.[r];i&&(e[n].fields[r].fieldName=i)}}return e}const pG=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function mG(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}const hG=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function gG(e){let t=hG.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`years`:case`year`:case`yrs`:case`yr`:case`y`:i=n*315576e5;break;case`months`:case`month`:case`mo`:i=n*2592e6;break;case`weeks`:case`week`:case`w`:i=n*6048e5;break;case`days`:case`day`:case`d`:i=n*864e5;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*36e5;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*6e4;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*1e3;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function _G(e){return Math.round(gG(e)/1e3)}const vG=We({session:QW.loose(),user:$W.loose(),updatedAt:Le(),version:k().optional()}),yG=A({session:ze(k(),rt()),expiresAt:Le(),signature:k()});function bG(e){let t=ye(e);if(t===null)return null;let n=vG.safeParse(t);return n.success?n.data:(C.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function xG(e){let t=yG.safeParse(e);return t.success?t.data:null}function SG(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function CG(e){if(!e)return[];let t=[],n=0,r=0;for(;r<e.length;){if(e[r]===`,`){let i=r+1;for(;i<e.length&&e[i]===` `;)i++;for(;i<e.length&&e[i]!==`=`&&e[i]!==`;`&&e[i]!==`,`;)i++;if(i<e.length&&e[i]===`=`){let i=e.slice(n,r).trim();for(i&&t.push(i),n=r+1;n<e.length&&e[n]===` `;)n++;r=n;continue}}r++}let i=e.slice(n).trim();return i&&t.push(i),t}function wG(e){let t=/* @__PURE__ */ new Map;return CG(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=DG(a.join(`=`));if(!i)return;let s={value:SG(o)};r.forEach(e=>{let[t,...n]=e.split(`=`),r=n.join(`=`),i=t.trim().toLowerCase();switch(i){case`max-age`:s[`max-age`]=r?parseInt(r.trim(),10):void 0;break;case`expires`:s.expires=r?new Date(r.trim()):void 0;break;case`domain`:s.domain=r?r.trim():void 0;break;case`path`:s.path=r?r.trim():void 0;break;case`secure`:s.secure=!0;break;case`httponly`:s.httponly=!0;break;case`samesite`:s.samesite=r?r.trim().toLowerCase():void 0;break;case`partitioned`:s.partitioned=!0;break;default:s[i]=!r||r.trim()}}),t.set(i,s)}),t}const TG=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,EG=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function DG(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function OG(e){let t=0,n=e.length;for(;t<n;){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}for(;n>t;){let t=e.charCodeAt(n-1);if(t!==32&&t!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)}function kG(e){let t=/* @__PURE__ */ new Map;if(e.length<2)return t;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e===-1)continue;let r=OG(n.slice(0,e)),i=DG(OG(n.slice(e+1)));TG.test(r)&&EG.test(i)&&t.set(r,SG(i))}return t}function AG(e){let t={clockTolerance:15,audience:e?.audience??`better-auth:session-cache`};return e?.issuer&&(t.issuer=e.issuer),t}function jG(e){let t=bG(e);return!t||typeof e.iss!=`string`||!e.iss||e.sub!==t.user.id||e.sid!==t.session.token?null:{...e,...t}}const MG={name:`HMAC`,hash:`SHA-256`},NG=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await PU().importKey(`raw`,t,MG,!1,[`sign`,`verify`])},PG=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await PU().verify(MG,n,i,new TextEncoder().encode(t))}catch{return!1}},FG=async(e,t)=>{let n=await NG(t),r=await PU().sign(MG.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},IG=async(e,t)=>{let n=await FG(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},LG=/^application\/([a-z0-9.+-]*\+)?json/i;async function RG(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new O(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new O(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(LG.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new O(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function zG(e){return e instanceof O||e?.name===`APIError`}function BG(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function VG(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function HG(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}const UG={secure:`__Secure-`,host:`__Host-`},WG=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return UG[t]+e};function GG(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=/* @__PURE__ */ new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,BG(n))}n=i+1}return t}function KG(e,t,n={}){let r=WG(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function qG({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}const JG=(e,t,n)=>(t=encodeURIComponent(t),qG(KG(e,t,n))),YG=async(e,t,n,r)=>(t=await IG(t,n),qG(KG(e,t,r)));async function XG(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:ZG(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:ZG(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function ZG(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}const QG=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await XG(t,e);if(o)throw new Pe(o.message,o.issues);let s=e.headers===void 0?`request`in e&&HG(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?GG(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=WG(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=WG(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await PG(s,o,await NG(t))?o:!1},setCookie:(e,t,n)=>{let i=JG(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await YG(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new O(`FOUND`,void 0,r)),error:(e,t,n)=>new O(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function $G(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function eK(e){let t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function tK(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}const nK=/* @__PURE__ */ new Set(/* @__PURE__ */ `host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function rK(e){for(let t of nK)e.delete(t)}function iK(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function aK(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);rK(n),iK(e.headers,n)}return e}if(tK(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(iK(i,r?.headers),iK(i,e.headers),t?.headers){let e=new Headers(t.headers);rK(e),iK(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if(zG(e))return aK(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return rK(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):$G(e)&&(n=eK(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function oK(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new Ne(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new Ne(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await VG(QG(t,{options:i,path:r}));if(o)throw o instanceof Pe?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new O(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(zG(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?aK(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function sK(e,t){return[...e??[],...t??[]]}oK.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return oK(n,{...r,use:sK(r.use,e?.use)},i)}let[n,r]=t;return oK({...n,use:sK(n.use,e?.use)},r)}return t};function cK(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await QG(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw zG(e)&&Object.defineProperty(e,Fe,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}cK.create=e=>{function t(t,n){if(typeof t==`function`)return cK({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return cK({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};const lK={};function uK(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function dK(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof $e&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof $e&&t.push({name:e,in:`query`,schema:{type:uK(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function fK(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof $e||e.body instanceof Ge)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof $e&&(n[e]={type:uK(t),description:t.description},t instanceof Ge||r.push(e))}),{required:e.body instanceof Ge?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function pK(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function mK(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(lK[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:dK(n),responses:pK(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=fK(n);lK[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:dK(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:pK(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:lK}}const hK=(e,t)=>`<!doctype html>
|
|
31
|
+
<html>
|
|
32
|
+
<head>
|
|
33
|
+
<title>Scalar API Reference</title>
|
|
34
|
+
<meta charset="utf-8" />
|
|
35
|
+
<meta
|
|
36
|
+
name="viewport"
|
|
37
|
+
content="width=device-width, initial-scale=1" />
|
|
38
|
+
</head>
|
|
39
|
+
<body>
|
|
40
|
+
<script
|
|
41
|
+
id="api-reference"
|
|
42
|
+
type="application/json">
|
|
43
|
+
${JSON.stringify(e)}
|
|
44
|
+
<\/script>
|
|
45
|
+
<script>
|
|
46
|
+
var configuration = {
|
|
47
|
+
favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
|
|
48
|
+
theme: ${t?.theme||`saturn`},
|
|
49
|
+
metaData: {
|
|
50
|
+
title: ${t?.title||`Open API Reference`},
|
|
51
|
+
description: ${t?.description||`Better Call Open API`},
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
document.getElementById('api-reference').dataset.configuration =
|
|
55
|
+
JSON.stringify(configuration)
|
|
56
|
+
<\/script>
|
|
57
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
|
|
58
|
+
</body>
|
|
59
|
+
</html>`,gK=/* @__PURE__ */ (()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function _K(){return{root:{key:``},static:new gK}}function vK(e){let t=0,n=0;for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===92)t++;else if(r===40)n++;else if(r===41&&n>0)n--;else if(r===123&&n===0)break}if(t>=e.length)return;let r=t+1;for(n=0;r<e.length;r++){let t=e.charCodeAt(r);if(t===92)r++;else if(t===40)n++;else if(t===41&&n>0)n--;else if(t===125&&n===0)break}if(r>=e.length)return;let i=e[r+1],a=i===`?`||i===`+`||i===`*`;return[e.slice(0,t),e.slice(t+1,r),e.slice(r+(a?2:1)),a?i:void 0]}function yK(e){if(!e.includes(`{`))return;let t=vK(e);if(!t)return;let[n,r,i,a]=t;if(!a)return[n+r+i];if(a===`?`)return[n+r+i,n+i];if(r.includes(`/`))throw Error(`unsupported group repetition across segments`);return[`${n}(?:${r})${a}${i}`]}function bK(e){return`__rou3_unnamed_${e}`}function xK(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:`__rou3_esc_`+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function SK(e){return e.charCodeAt(0)===95?e.startsWith(`__rou3_esc_`)?e.slice(11).replace(/__|_h/g,e=>e===`__`?`_`:`-`):e.startsWith(`__rou3_unnamed_`)?e.slice(15):e:e}function CK(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===92)n++;else if(r===40)t++;else if(r===41&&t>0)t--;else if(r===42&&t===0)return!0}return!1}function wK(e,t,n=bK){let r=0,i=t,a=``;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);o===92?(a+=e[t],t+1<e.length&&(a+=e[++t])):o===40?(r++,a+=e[t]):o===41&&r>0?(r--,a+=e[t]):a+=o===42&&r===0?`(?<${n(i++)}>[^/]*)`:e[t]}return[a,i]}function TK(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function EK(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||CK(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function DK(e){for(let t=0;t<e.length;t++){let n=e[t].charCodeAt(e[t].length-1);if(n!==63&&n!==43&&n!==42)continue;let r=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!r)continue;let i=e.slice(0,t),a=e.slice(t+1);if(r[2]===`?`)return[`/`+i.concat(r[1]).concat(a).join(`/`),`/`+i.concat(a).join(`/`)];let o=r[1].match(/:([\w-]+)/)?.[1]||`_`,s=`/`+[...i,`**:${o}`,...a].join(`/`),c=`/`+[...i,...a].join(`/`);return r[2]===`+`?[s]:[s,c]}}function OK(e){if(!e.includes(`/.`))return e;let t=[];for(let n of e.split(`/`))if(n===`.`)continue;else n===`..`&&t.length>1?t.pop():t.push(n);return t.join(`/`)||`/`}function kK(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function AK(e){let t=kK(e);for(;t[t.length-1]===``;)t.pop();return t}function jK(e,t){let n=new gK;for(let[r,i]of t){let t=r<0?e.slice(-(r+1)).join(`/`):e[r];if(typeof i==`string`)n[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)n[SK(t)]=e.groups[t]}}return n}function MK(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=yK(n);if(i){for(let n of i)MK(e,t,n,r);return}n=TK(n);let a=AK(n),o=DK(a);if(o){for(let n of o)MK(e,t,n,r);return}let s=e.root,c=0,l=[],u=[];for(let e=0;e<a.length;e++){let t=a[e],n=EK(t);if(n===2){s.wildcard||(s.wildcard={key:`**`}),s=s.wildcard,l.push([-(e+1),t.split(`:`)[1]||`_`,t.length===2]);break}if(n===1){if(s.param||(s.param={key:`*`}),s=s.param,t===`*`)l.push([e,String(c++),!0]);else if(t.includes(`(`)||t.includes(`:`,1)||!/^:[\w-]+$/.test(t)){let[n,r]=NK(t,c);c=r,u[e]=n,s.hasRegexParam=!0,l.push([e,n,!1])}else l.push([e,t.slice(1),!1]);continue}t=a[e]=n;let r=s.static?.[t];if(r)s=r;else{let e={key:t};s.static||(s.static=new gK),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new gK;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function NK(e,t=0){let n=t,r=``,i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40)i++;else if(n===41&&i>0)i--;else if(n===92&&i===0&&t+1<e.length){let n=e[t+1];if(n!==`:`&&n!==`(`&&n!==`*`&&n!==`\\`){r+=``+n,t++;continue}}else if(n===46&&i===0){r+=`\\.`;continue}r+=e[t]}[r,n]=wK(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${xK(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${bK(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function PK(e,t=``,n,r){r?.normalize&&(n=OK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=e.static[n];if(i&&i.methods){let e=i.methods[t]||i.methods[``];if(e!==void 0)return e[0]}let a=kK(n),o=FK(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?jK(a,o.paramsMap):void 0}}function FK(e,t,n,r){if(r===n.length){if(e.methods){let r=IK(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&IK(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&IK(e.wildcard.methods,t,n,!0,!0)||void 0}let i=n[r];if(e.static){let a=e.static[i];if(a){let e=FK(a,t,n,r+1);if(e)return e}}if(e.param){let i=FK(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return IK(e.wildcard.methods,t,n,!0,!1)}function IK(e,t,n,r,i){let a=e[t]||e[``];if(!a)return;let o=a[0];if(a.length===1&&o.paramsRegexp.length===0){if(!i)return o;let e=o.paramsMap;return e?.[e.length-1]?.[2]?o:void 0}let s,c=-1;for(let e of a){let t=e.paramsMap,a=t?.[t.length-1]?.[2];if(i&&!a)continue;let o=r&&t&&!a?1:0,l=e.paramsRegexp;for(let e=0;e<l.length;e++)if(l[e]){if(!l[e].test(n[e])){o=-1;break}o++}o>c&&(s=e,c=o)}return s}function LK(e,t=``,n,r){r?.normalize&&(n=OK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=kK(n),a=RK(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?jK(i,e.paramsMap):void 0}))}function RK(e,t,n,r,i=[]){let a=n[r];if(e.wildcard&&e.wildcard.methods){let a=e.wildcard.methods[t]||e.wildcard.methods[``];if(a){if(r<n.length)zK(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}zK(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(RK(e.param,t,n,r+1,i),e.param.hasRegexParam)for(let e=i.length-1;e>=o;e--)i[e].paramsRegexp[r]?.test(a)===!1&&i.splice(e,1)}else if(e.param.methods){let n=e.param.methods[t]||e.param.methods[``];if(n){let e=[];for(let t of n){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}zK(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&RK(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&zK(i,n,e.key===`*`)}return i}function zK(e,t,n){t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:r,paramsMap:i}=e;for(let e=0;e<r.length;e++)r[e]&&t++;return n&&i&&!i[i.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0]));for(let n of t)e.push(n)}const BK=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=oK(n.path,{method:`GET`},async t=>{let r=await mK(e);return new Response(hK(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=_K(),r=_K();for(let t of Object.values(e)){if(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY)continue;let e=Array.isArray(t.options?.method)?t.options.method:[t.options?.method];for(let r of e)MK(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)MK(r,`*`,e,n);let i=t?.basePath&&t.basePath!==`/`?t.basePath.replace(/\/+$/,``):``,a=async e=>{let a=new URL(e.url),o=a.pathname,s;if(i){if(!o.startsWith(`${i}/`))return new Response(null,{status:404,statusText:`Not Found`});s=o.slice(i.length)}else s=o;if(s.length===0||/\/{2,}/.test(s))return new Response(null,{status:404,statusText:`Not Found`});let c=PK(n,e.method,s);if(s.endsWith(`/`)!==c?.data?.path?.endsWith(`/`)&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:`Not Found`});let l={};a.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let u=c.data;try{let n=u.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:s,method:e.method,headers:e.headers,params:c.params?{...c.params}:{},request:e,body:u.options.disableBody?void 0:await RG(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=LK(r,`*`,s);if(a?.length)for(let{data:e,params:t}of a){let n=await e({...i,params:t?{...t}:{},asResponse:!1});if(n instanceof Response)return n}return await u(i)}catch(n){if(t?.onError)try{let r=await t.onError(n,e);if(r instanceof Response)return aK(r)}catch(e){if(zG(e))return aK(e);throw e}if(t?.throwError)throw n;return zG(n)?aK(n):(console.error(`# SERVER_ERROR: `,n),new Response(null,{status:500,statusText:`Internal Server Error`}))}};return{handler:async e=>{let n=await t?.onRequest?.(e);if(n instanceof Response)return n;let r=HG(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}},VK=4050;function HK(e,t){return VK-JG(e,``,{...t}).length}function UK(e,t){let n=`${e}.`;if(!t.startsWith(n))return null;let r=t.slice(n.length),i=Number(r);return!Number.isSafeInteger(i)||i<0||String(i)!==r?null:i}function WK(e,t){let n={},r=kG(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||UK(e,t)!==null)&&(n[t]=i);return n}function GK(e,t,n,r){let i=HK(`${t.name}.99`,t.attributes),a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return n[t.name]=t.value,[t];if(a>100)return r.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let o=[];for(let e=0;e<a;e++){let r=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:r,value:s}),n[r]=s}return r.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${VK} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function KK(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}const qK=e=>(t,n,r)=>{let i=WK(t,r),a=r.context.logger,o=()=>{let e=KK(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=GK(e,{name:t,value:r,attributes:{...n,...s}},i,a);for(let e of l)c[e.name]=e;return Object.values(c)},clean(){return Object.values(o())},setCookies(e){for(let t of e)r.setCookie(t.name,t.value,t.attributes)}}},JK=qK(`Session`),YK=qK(`Account`);function XK(e,t){let n=e.getCookie(t);if(n)return n;let r=[],i=e.headers?.get(`cookie`);if(!i)return null;for(let[e,n]of kG(i)){let i=UK(t,e);i!==null&&r.push({index:i,value:n})}return r.length>0?(r.sort((e,t)=>e.index-t.index),r.map(e=>e.value).join(``)):null}async function ZK(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await wU(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=YK(n.name,r,e);a.setCookies(a.chunk(i,r))}async function QK(e){let t=XK(e,e.context.authCookies.accountData.name);if(t){let n=ye(await EU(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}const $K=at(A({disableCookieCache:XW().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:XW().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()})),eq=/* @__PURE__ */ new Map,tq=new TextEncoder,nq={decode:(e,t=`utf-8`)=>(eq.has(t)||eq.set(t,new TextDecoder(t)),eq.get(t).decode(e)),encode:e=>tq.encode(e)},rq=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>PU().importKey(`raw`,le(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await PU().sign(`HMAC`,e,le(r));return t===`hex`?xe.encode(i):t===`base64`?he.encode(i):t===`base64url`||t===`base64urlnopad`?me.encode(i,{padding:t!==`base64urlnopad`}):i},verify:async(e,r,i)=>(typeof e==`string`&&(e=await n.importKey(e,`verify`)),t===`hex`&&(i=typeof i==`string`?xe.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await he.decode(i)),PU().verify(`HMAC`,e,le(i),le(r)))};return n};function iq(e){let t=typeof e.baseURL==`string`?e.baseURL:void 0,n=typeof e.baseURL==`object`&&e.baseURL!==null?e.baseURL.protocol:void 0,r=(e.advanced?.useSecureCookies===void 0?n===`https`||n!==`http`&&(t?t.startsWith(`https://`):ae):e.advanced?.useSecureCookies)?`__Secure-`:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!WH(e.baseURL))throw new D(`baseURL is required when crossSubdomainCookies are enabled.`);function o(t,n={}){let o=e.advanced?.cookiePrefix||`better-auth`,s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${r}${s}`,attributes:{secure:!!r,sameSite:`lax`,path:`/`,httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...n,...c}}}return o}function aq(e){let t=iq(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||_G(`7d`)}),r=t(`session_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),i=t(`account_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),a=t(`dont_remember`);return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:r.name,attributes:r.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function oq(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=eG(t.session,e.context.options.session?.additionalFields),i=rG(e.context.options,t.user),a=e.context.options.session?.cookieCache?.version,o=`1`;if(a){if(typeof a==`string`)o=a;else if(typeof a==`function`){let e=a(t.session,t.user);o=mG(e)?await e:e}}let s={session:r,user:i,updatedAt:Date.now(),version:o},c={...e.context.authCookies.sessionData.attributes,maxAge:n?void 0:e.context.authCookies.sessionData.attributes.maxAge},l=pG(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,d;if(u===`jwe`)d=await wU(s,e.context.secretConfig,`better-auth-session`,c.maxAge||300);else if(u===`jwt`){let t=e.context.sessionConfig.cookieCacheSigner;d=t?await t.sign(e,s,c.maxAge||300):await gU(s,e.context.secret,c.maxAge||300)}else d=me.encode(JSON.stringify({session:s,expiresAt:l,signature:await rq(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let f=JK(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(d,c)),e.context.options.account?.storeAccountCookie&&!uq(e,e.context.authCookies.accountData.name)){let n=await QK(e);if(n){if(!qW(e.context.options)||n.userId===t.user.id)await ZK(e,n);else{dq(e,e.context.authCookies.accountData);let t=YK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function sq(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await EU(t,e.context.secretConfig,`better-auth-session`),r=bG(n);return r?{session:r,expiresAt:n?.exp?n.exp*1e3:Date.now()}:null}if(n===`jwt`){let n=e.context.sessionConfig.cookieCacheSigner;if(n){let r=await n.verify(e,t);return r?{session:r.payload,expiresAt:r.expiresAt}:null}let r=await _U(t,e.context.secret),i=bG(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=xG(ye(nq.decode(me.decode(t))));if(!r||!await rq(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=bG(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function cq(e,t,n,r){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);n=n===void 0?!!i:n;let a=e.context.authCookies.sessionToken.attributes,o=n?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...r}),n&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,`true`,e.context.secret,e.context.authCookies.dontRememberToken.attributes),await oq(e,t,n),e.context.setNewSession(t)}function lq(e,t){let n=e,r=/* @__PURE__ */ new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t=typeof e.getSetCookie==`function`?e.getSetCookie():CG(e.get(`set-cookie`)||``);if(!t.length)continue;let n=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));if(n.length!==t.length){e.delete(`set-cookie`);for(let t of n)e.append(`set-cookie`,t)}}}function uq(e,t){let n=e,r=/* @__PURE__ */ new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if((typeof e.getSetCookie==`function`?e.getSetCookie():CG(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function dq(e,t){lq(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function fq(e,t){if(dq(e,e.context.authCookies.sessionToken),dq(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){dq(e,e.context.authCookies.accountData);let t=YK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&dq(e,e.context.createAuthCookie(`oauth_state`));let n=JK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||dq(e,e.context.authCookies.dontRememberToken)}const pq=_e(`better-auth:oauth-encryption:v1`);function mq(e,t){return m(rU(hU,_e(e),pq,_e(`better-auth:${t}:v1`),32))}function hq(e,t){return typeof e==`string`?mq(e,t):{keys:new Map(Array.from(e.keys,([e,n])=>[e,mq(n,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:mq(e.legacySecret,t)}}}const gq=We({callbackURL:k(),codeVerifier:k(),errorURL:k().optional(),newUserURL:k().optional(),expiresAt:Le(),oauthState:k().optional(),link:A({email:k(),userId:JW()}).optional(),requestSignUp:Je().optional(),idTokenNonce:k().optional(),serverContext:ze(k(),rt()).optional()}),_q=e=>`auth-state:${e}`;new Set(Object.keys(gq.shape));var vq=class extends D{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function yq(e,t,n){let r=ZH(32);if(e.context.oauthConfig.storeStateStrategy===`cookie`){let i={...t,oauthState:r},a=await VW({key:hq(e.context.secretConfig,`oauth-state-cookie`),data:JSON.stringify(i)}),o=e.context.createAuthCookie(n?.cookieName??`oauth_state`,{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:r,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(n?.cookieName??`state`,{maxAge:300});await e.setSignedCookie(i.name,r,e.context.secret,i.attributes);let a=/* @__PURE__ */ new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:r}),identifier:_q(r),expiresAt:a}))throw new vq(`Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database`,{code:`state_generation_error`});return{state:r,codeVerifier:t.codeVerifier}}async function bq(e,t,n){if(!t)throw new vq(`State not found in OAuth callback`,{code:`state_not_found`});let r=e.context.oauthConfig.storeStateStrategy,i;if(r===`cookie`){let r=e.context.createAuthCookie(n?.cookieName??`oauth_state`),a=e.getCookie(r.name);if(!a)throw new vq(`State mismatch: auth state cookie not found`,{code:`state_mismatch`,details:{state:t}});try{let t=await HW({key:hq(e.context.secretConfig,`oauth-state-cookie`),data:a});i=gq.parse(JSON.parse(t))}catch(e){throw new vq(`State invalid: Failed to decrypt or parse auth state`,{code:`state_invalid`,details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new vq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});dq(e,r)}else{let r=await e.context.internalAdapter.findVerificationValue(_q(t));if(!r)throw new vq(`State mismatch: verification not found`,{code:`state_mismatch`,details:{state:t}});if(i=gq.parse(JSON.parse(r.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new vq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});let a=e.context.createAuthCookie(n?.cookieName??`state`),o=await e.getSignedCookie(a.name,e.context.secret);if(!(n?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new vq(`State mismatch: State not persisted correctly`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});dq(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(_q(t))}if(i.expiresAt<Date.now())throw new vq(`Invalid state: request expired`,{code:`state_mismatch`,details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function xq(e,t){let n;try{n=new URL(e).pathname.replace(/\/+$/,``)||`/`}catch{return`/`}let r=t.replace(/\/+$/,``);return r===``?n:n===r?`/`:n.startsWith(r+`/`)?n.slice(r.length).replace(/\/+$/,``)||`/`:n}const Sq=`https://better-auth.invalid`;function Cq(e,t){let n=e.startsWith(`/`);if(e.startsWith(`//`)||e.startsWith(`/\\`))throw TypeError(`Expected an absolute or root-relative URL`);let r=n?new URL(e,Sq):new URL(e);if(n&&r.origin!==Sq)throw TypeError(`Expected an absolute or root-relative URL`);let i=t.toString();if(!i)return e;let a=r.search.endsWith(`&`)?``:`&`;return r.search=r.search?`${r.search}${a}${i}`:i,n?r.href.slice(r.origin.length):r.href}const wq=[`javascript:`,`data:`,`vbscript:`],Tq={NO_CODE:`no_code`,PROVIDER_NOT_FOUND:`oauth_provider_not_found`,ISSUER_MISSING:`issuer_missing`,ISSUER_MISMATCH:`issuer_mismatch`,INVALID_CODE:`invalid_code`,NONCE_BINDING_MISSING:`nonce_binding_missing`,UNABLE_TO_GET_USER_INFO:`unable_to_get_user_info`,NO_CALLBACK_URL:`no_callback_url`,UNABLE_TO_LINK_ACCOUNT:`unable_to_link_account`,EMAIL_DOES_NOT_MATCH:`email_does_not_match`,ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:`account_already_linked_to_different_user`,EMAIL_NOT_FOUND:`email_not_found`,EMAIL_NOT_VERIFIED:`email_not_verified`};function Eq(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=Cq(t,i);throw e.redirect(a)}function Dq(e,t){return`${t?.source===`generic`?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source===`id_token`?` in the id token`:``}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}const{get:Oq,set:kq}=SH(()=>null),Aq=async()=>await Oq(),{get:jq,set:Mq}=SH(()=>null),Nq=async e=>{await Mq({...await jq()??{},...e})};function Pq(e){return e.requiresIdTokenNonce?ZH(32):void 0}async function Fq(e,t){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw E.from(`BAD_REQUEST`,Y.CALLBACK_URL_REQUIRED);let r=t?.codeVerifier??ZH(128),i=await jq(),a=i&&Object.keys(i).length?i:void 0,o={...t?.additionalData?t.additionalData:{},callbackURL:n,codeVerifier:r,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:a,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await kq(o);try{return yq(e,o)}catch(t){throw e.context.logger.error(`Failed to create verification`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`Unable to create verification`,cause:t})}}async function Iq(e){let t=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,r;try{r=await bq(e,t)}catch(t){e.context.logger.error(`Failed to parse state`,t);let r=`internal_server_error`,i=n;t instanceof vq&&(r=t.code===`state_security_mismatch`?`state_mismatch`:t.code,i=t.errorURL||n),Eq(e,i,r)}return r.errorURL||(r.errorURL=n),r&&await kq(r),r}const Lq={scope:`server`};function Rq(e){return e instanceof O||e instanceof E||e?.name===`APIError`}const zq={"Cache-Control":`no-store`,Pragma:`no-cache`};function Bq(e,t){Rq(t)&&e&&Object.defineProperty(t,Fe,{enumerable:!1,configurable:!0,value:e,writable:!1})}const Vq=cK(async()=>({})),Hq=cK.create({use:[Vq,cK(async()=>({}))]}),Uq=oK.create({use:[Vq]});function Wq(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(zq))t.setHeader(e,n);try{return await _H(t,()=>e(t))}catch(e){throw Bq(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return Uq(t,n,Wq(r,n))}let[t,n]=e;return Uq(t,Wq(n,t))}function Gq(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(Gq(e),t);const Kq=/[\u0000-\u001f\u007f-\u009f]/,qq=`https://better-auth.invalid`,Jq=/%2[fF]|%5[cC]/,Yq=e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let n=[];for(let e of t.split(`/`))e===`..`?n.pop():e!==`.`&&e!==``&&n.push(e);return n.length>0?`/${n.join(`/`)}`:``},Xq=e=>{if(Kq.test(e))return null;let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1),i=``;if(r.startsWith(`//`)){r=r.slice(2);let e=r.search(/[/?#]/);e===-1?(i=r,r=``):(i=r.slice(0,e),r=r.slice(e))}let a=r.search(/[?#]/),o=Yq(a===-1?r:r.slice(0,a));return{scheme:n,authority:i.toLowerCase(),path:o}},Zq=e=>{if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||Kq.test(e))return!1;let t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t);if(Jq.test(n))return!1;try{return new URL(e,qq).origin===qq}catch{return!1}},Qq=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths===!0&&Zq(e);if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return NH(t)(VH(e)||e);let n=UH(e);return n?NH(t)(n):!1}let r=HH(e);if(r===`http:`||r===`https:`||!r)return t===VH(e);let i=Xq(e),a=Xq(t);return!i||!a||i.scheme!==a.scheme||a.authority&&i.authority!==a.authority?!1:!a.path||i.path===a.path||i.path.startsWith(`${a.path}/`)};function $q(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function eJ(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function tJ(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let n=new URL(e.context.baseURL).pathname,r=xq(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}const nJ=$q(function(){},`disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.`),rJ=Hq(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await aJ(e),tJ(e)))return;let{body:t,query:n}=e,r=t?.callbackURL||n?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,n)=>{if(t){if(typeof t!=`string`)throw E.fromStatus(`BAD_REQUEST`,{message:`Invalid ${n}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:n!==`origin`}))throw e.context.logger.error(`Invalid ${n}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,Y.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,Y.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,Y.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})}};r&&s(r,`callbackURL`),i&&s(i,`redirectURL`),a&&s(a,`errorCallbackURL`),o&&s(o,`newUserCallbackURL`)}),iJ=e=>Hq(async t=>{if(!t.request||tJ(t))return;let n=e(t),r=(e,n)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:n!==`origin`}))throw t.context.logger.error(`Invalid ${n}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,Y.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,Y.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,Y.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})},i=Array.isArray(n)?n:[n];for(let e of i)r(e,`callbackURL`)});async function aJ(e,t=!1){let n=e.request?.headers;if(!n||!e.request)return;let r=n.get(`origin`),i=r||n.get(`referer`)||``,a=n.has(`cookie`);if(e.context.skipCSRFCheck)return;if(eJ(e)){e.context.options.advanced?.disableOriginCheck===!0&&nJ();return}if(tJ(e)||!(t||a))return;let o=r===`null`&&n.get(`sec-fetch-site`)===`same-origin`?BH(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(o?VH(o):void 0)??i;if(!s||s===`null`)throw E.from(`FORBIDDEN`,Y.MISSING_OR_NULL_ORIGIN);let c=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!c.some(e=>Qq(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${c}`),E.from(`FORBIDDEN`,Y.INVALID_ORIGIN)}const oJ=Hq(async e=>{e.request&&await sJ(e)});async function sJ(e){let t=e.request;if(!t||e.context.skipCSRFCheck||eJ(e))return;let n=t.headers;if(n.has(`cookie`))return await aJ(e);let r=n.get(`Sec-Fetch-Site`),i=n.get(`Sec-Fetch-Mode`),a=n.get(`Sec-Fetch-Dest`);if(r&&r.trim()||i&&i.trim()||a&&a.trim()){if(r===`cross-site`&&i===`navigate`)throw e.context.logger.error(`Blocked cross-site navigation login attempt (CSRF protection)`,{secFetchSite:r,secFetchMode:i,secFetchDest:a}),E.from(`FORBIDDEN`,Y.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await aJ(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await aJ(e,!0)}const cJ=He(),lJ=Qe();function uJ(e){return dJ(e)||fJ(e)}function dJ(e){return qe(cJ,e)}function fJ(e){return qe(lJ,e)}function pJ(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(dJ(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&dJ(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=mJ(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function mJ(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function hJ(e,t){let n=mJ(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function gJ(e,t={}){if(dJ(e)||!fJ(e))return e.toLowerCase();let n=pJ(e);return n?n.toLowerCase():hJ(e,t.ipv6Subnet??64)}function _J(e){if(dJ(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!fJ(e))return null;let t=pJ(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=mJ(e),r=/* @__PURE__ */ new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(n[e]??`0`,16);r[e*2]=t>>8&255,r[e*2+1]=t&255}return r}const vJ=/^\d+$/;function yJ(e){let t=e.lastIndexOf(`/`),n=_J(t===-1?e:e.slice(0,t));if(!n)return null;let r=n.length*8;if(t===-1)return{bytes:n,prefix:r};let i=e.slice(t+1);if(!vJ.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function bJ(e,t){if(e.length!==t.bytes.length)return!1;let n=t.prefix;for(let r=0;r<e.length&&n>0;r++){let i=n>=8?8:n,a=i===8?255:255<<8-i&255;if(((e[r]??0)&a)!==((t.bytes[r]??0)&a))return!1;n-=8}return!0}function xJ(e){return e.filter(e=>yJ(e)===null)}function SJ(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(yJ).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?_J(i):null;if(!i||!a)return null;if(!r.some(e=>bJ(a,e)))return gJ(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!uJ(i)?null:gJ(i,{ipv6Subnet:t.ipv6Subnet})}const CJ=[`x-forwarded-for`];function wJ(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||CJ;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=SJ(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return v()||p()?`127.0.0.1`:null}function TJ(e,t){return`${e}|${t}`}const EJ=/* @__PURE__ */ new Map,DJ=1e5;function OJ(){let e=Date.now();for(let[t,n]of EJ)e>=n.expiresAt&&EJ.delete(t);if(EJ.size<=DJ)return;let t=EJ.size-DJ,n=0;for(let e of EJ.keys())if(EJ.delete(e),++n>=t)break}function kJ(e,t,n){let r=t.window*1e3;return e?n-e.lastRequest>=r?{next:{...e,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:jJ(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:{next:{key:``,count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null}}function AJ(e){return new Response(JSON.stringify({message:`Too many requests. Please try again later.`}),{status:429,statusText:`Too Many Requests`,headers:{"Content-Type":`application/json`,"X-Retry-After":e.toString()}})}function jJ(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function MJ(e){let t=`rateLimit`,n=e.adapter,r=Math.max(...NJ(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return r&&(r.lastRequest=Number(r.lastRequest)),r},a=async(e,s)=>{s.window>r&&(r=s.window);let c=s.window*1e3,l=await i(e),u=Date.now();if(!l)try{return await n.create({model:t,data:{key:e,count:1,lastRequest:u}}),{allowed:!0,retryAfter:null}}catch(t){if(!await i(e))throw t;return a(e,s)}if(u-l.lastRequest>=c)return await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`lte`,value:l.lastRequest}],increment:{},set:{count:1,lastRequest:u}})?(await o(u),{allowed:!0,retryAfter:null}):a(e,s);let d=u-c;if(await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`gt`,value:d},{field:`count`,operator:`lt`,value:s.max}],increment:{count:1},set:{lastRequest:u}}))return{allowed:!0,retryAfter:null};let f=await i(e);return!f||u-f.lastRequest>=c?a(e,s):{allowed:!1,retryAfter:jJ(f.lastRequest,s.window)}},o=async i=>{let a=i-r*1e3;await e.runInBackgroundOrAwait(n.deleteMany({model:t,where:[{field:`lastRequest`,operator:`lt`,value:a}]}).then(()=>void 0).catch(t=>e.logger.error(`Error pruning rate limit rows`,t)))};return{consume:a}}function NJ(e){let t=[e.rateLimit.window,...RJ().map(e=>e.window)];for(let n of e.options.plugins||[])n.rateLimit&&t.push(...n.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let n of Object.values(e.rateLimit.customRules))n&&typeof n!=`function`&&t.push(n.window);let n=t.filter(e=>Number.isFinite(e)&&e>0);return n.length>0?n:[e.rateLimit.window]}function PJ(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let n=e.rateLimit.storage;if(n===`secondary-storage`){let t=t=>t??e.options.rateLimit?.window??10,n=e.options.secondaryStorage?.increment;if(!n)throw new D(`Secondary-storage rate limiting requires SecondaryStorage.increment.`);return{consume:async(e,r)=>await n(e,t(r.window))<=r.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:r.window}}}if(n===`memory`){let t=t=>t??e.options.rateLimit?.window??10;return{async consume(e,n){OJ();let r=Date.now(),i=EJ.get(e),a=kJ(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&EJ.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return MJ(e)}let FJ=!1;async function IJ(e,t){let n=new URL(t.baseURL).pathname,r=xq(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=wJ(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!FJ&&(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),FJ=!0);let s=TJ(o??`no-trusted-ip`,r),c=RJ().find(e=>e.pathMatcher(r));c&&(i=c.window,a=c.max);for(let e of t.options.plugins||[])if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(r));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let n=Object.keys(t.rateLimit.customRules).find(e=>e.includes(`*`)?NH(e)(r):e===r);if(n){let r=t.rateLimit.customRules[n],o=typeof r==`function`?await r(e,{window:i,max:a}):r;if(o&&(i=o.window,a=o.max),o===!1)return null}}return{key:s,currentWindow:i,currentMax:a}}async function LJ(e,t){if(!t.rateLimit.enabled)return;let n=await IJ(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=PJ(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return AJ(l??i)}function RJ(){return[{pathMatcher(e){return e.startsWith(`/sign-in`)||e.startsWith(`/sign-up`)||e.startsWith(`/change-password`)||e.startsWith(`/change-email`)},window:10,max:3},{pathMatcher(e){return e===`/request-password-reset`||e===`/send-verification-email`||e.startsWith(`/forget-password`)||e===`/email-otp/send-verification-otp`||e===`/email-otp/request-password-reset`},window:60,max:3}]}const{get:zJ,set:xfe}=SH(()=>!1),BJ=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:$K,requireHeaders:!0,metadata:{openapi:{operationId:`getSession`,description:`Get the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:[`object`,`null`],properties:{session:{$ref:`#/components/schemas/Session`},user:{$ref:`#/components/schemas/User`}},required:[`session`,`user`]}}}}}}}},async e=>{e.setHeader(`cache-control`,`no-store`),e.setHeader(`pragma`,`no-cache`);let t=e.context.options.session?.deferSessionRefresh,n=e.method===`POST`;if(n&&!t)throw E.from(`METHOD_NOT_ALLOWED`,Y.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let r=e.context.options.session?.cookieCache?.enabled===!0,i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i&&r)return null;let a=XK(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=JK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!i)return null;let o=r&&!e.query?.disableCookieCache,s=o&&a?await sq(e,a):null;o&&a&&!s&&dq(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,n=t.session.token!==i;if(!n){let r=e.context.options.session?.cookieCache?.version,i=`1`;if(r){if(typeof r==`string`)i=r;else if(typeof r==`function`){let e=r(t.session,t.user);i=e instanceof Promise?await e:e}}n=(t.version||`1`)!==i}if(!n){let e=Date.now(),r=new Date(t.session.expiresAt).getTime();n=s.expiresAt<e||!Number.isFinite(r)||r<e}if(n)dq(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=aG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=rG(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:n,user:r})}let r=s.expiresAt-Date.now(),i=n.updateAge*1e3,a=await zJ();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await oq(e,n,!1);let r=e.context.authCookies.sessionToken.attributes,i=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:i});let a=aG(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=rG(e.context.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)});return e.context.session={session:a,user:o},e.json({session:a,user:o})}let o=aG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=rG(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:o,user:l},e.json({session:o,user:l})}}let l=await e.context.internalAdapter.findSession(i);if(e.context.session=l,!l||l.session.expiresAt</* @__PURE__ */ new Date)return fq(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=aG(e.context.options,l.session),n=rG(e.context.options,l.user);return e.json({session:t,user:n})}let u=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge,f=l.session.expiresAt.valueOf()-u*1e3+d*1e3<=Date.now(),p=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,m=await zJ(),h=f&&!p&&!m;if(t&&!n){await oq(e,l,!!c);let t=aG(e.context.options,l.session),n=rG(e.context.options,l.user);return e.json({session:t,user:n,needsRefresh:h})}if(h){let t=await e.context.internalAdapter.updateSession(l.session.token,{expiresAt:pG(e.context.sessionConfig.expiresIn,`sec`),updatedAt:/* @__PURE__ */ new Date});if(!t)throw fq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await cq(e,{session:t,user:l.user},!1,{maxAge:n});let r=aG(e.context.options,t),i=rG(e.context.options,l.user);return e.json({session:r,user:i})}await oq(e,l,!!c);let g=aG(e.context.options,l.session),_=rG(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw Rq(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION,{cause:t}))}}),VJ=e=>GW(e.context.options),HJ=async(e,t)=>{if(e.context.session)return e.context.session;let n=await BJ()({...e,method:`GET`,asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return n?(n.headers&&n.headers.forEach((t,n)=>{let r=n.toLowerCase();r!==`cache-control`&&r!==`pragma`&&(r===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t))}),e.context.session=n.response,n.response):(e.context.session=null,null)},UJ=async e=>VJ(e)?(e.context.session=null,HJ(e,{disableCookieCache:!0})):HJ(e),WJ=Hq(async e=>{let t=await HJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),GJ=Hq(async e=>{let t=await UJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});Hq(async e=>{let t=await HJ(e);if(!t?.session&&(e.request||e.headers))throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});const KJ=Hq(async e=>{let t=await HJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});if(e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`FORBIDDEN`,Y.SESSION_NOT_FRESH)}return{session:t}}),qJ=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[KJ],requireHeaders:!0,metadata:{openapi:{operationId:`listUserSessions`,description:`List all active sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{$ref:`#/components/schemas/Session`}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>/* @__PURE__ */ new Date);return e.json(t.map(t=>aG(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),JJ=X(`/revoke-session`,{method:`POST`,body:A({token:k().meta({description:`The token to revoke`})}),use:[GJ],requireHeaders:!0,metadata:{openapi:{description:`Revoke a single session`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,description:`The token to revoke`}},required:[`token`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the session was revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),YJ=X(`/revoke-sessions`,{method:`POST`,use:[GJ],requireHeaders:!0,metadata:{openapi:{description:`Revoke all sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),XJ=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[GJ],metadata:{openapi:{description:`Revoke all other sessions for the user except the current one`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all other sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>/* @__PURE__ */ new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(n.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function ZJ(e){if(!e?.method)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`User validation source is required`});if(e.method===`oauth`&&!e.oauth?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`OAuth user validation source requires oauth.providerId`});if((e.method===`sso-oidc`||e.method===`sso-saml`)&&!e.sso?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`SSO user validation source requires sso.providerId`})}async function QJ(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;ZJ(t.source);let r;try{r=await n(t,e)}catch(t){throw e.context.logger.error(`validateUserInfo callback threw`,t),new E(`FORBIDDEN`,{code:`validation_failed`,message:`User validation failed`})}if(r?.error)throw new E(`FORBIDDEN`,{code:r.error,message:r.errorDescription||r.error})}const $J=async e=>{let t=await FU(`SHA-256`).digest(new TextEncoder().encode(e));return me.encode(new Uint8Array(t),{padding:!1})};async function eY(e,t){return!t||t===`plain`?e:t===`hashed`?$J(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function tY(e,t){if(t){if(typeof t==`object`&&`default`in t){if(t.overrides){for(let[n,r]of Object.entries(t.overrides))if(e.startsWith(n))return r}return t.default}return t}}function nY(e,t){let n=ue(t.options),r=t.hooks;async function i(t,i,a){let o=hH(),s=t;for(let{source:e,hooks:t}of r){let r=t[i]?.create?.before;if(r){let t=await n(`db create.before ${i}`,{[ve]:`create.before`,[Ce]:i,[be]:e},()=>r(s,o));if(t===!1)return null;typeof t==`object`&&`data`in t&&(s={...s,...t.data})}}let c=null;(!a||a.executeMainFn)&&(c=await(await TH(e)).create({model:i,data:s,forceAllowId:!0})),a?.fn&&(c=await a.fn(c??s));for(let{source:e,hooks:t}of r){let r=t[i]?.create?.after;r&&await OH(async()=>{await n(`db create.after ${i}`,{[ve]:`create.after`,[Ce]:i,[be]:e},()=>r(c,o))})}return c}async function a(t,i,a,o){let s=hH(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db update.before ${a}`,{[ve]:`update.before`,[Ce]:a,[be]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await TH(e)).update({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await OH(async()=>{await n(`db update.after ${a}`,{[ve]:`update.after`,[Ce]:a,[be]:e},()=>r(u,s))})}return u}async function o(t,i,a,o){let s=hH(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db updateMany.before ${a}`,{[ve]:`updateMany.before`,[Ce]:a,[be]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await TH(e)).updateMany({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await OH(async()=>{await n(`db updateMany.after ${a}`,{[ve]:`updateMany.after`,[Ce]:a,[be]:e},()=>r(u,s))})}return u}async function s(t,i,a){let o=hH(),s=null;try{s=(await(await TH(e)).findMany({model:i,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":e},()=>r(s,o))===!1)return null}let c=a?await a.fn(t):null,l=(!a||a.executeMainFn)&&s?await(await TH(e)).delete({model:i,where:t}):c;if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.after;r&&await OH(async()=>{await n(`db delete.after ${i}`,{[ve]:`delete.after`,[Ce]:i,[be]:e},()=>r(s,o))})}return l}async function c(t,i,a){let o=hH(),s=[];try{s=await(await TH(e)).findMany({model:i,where:t})}catch{}for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":t},()=>r(e,o))===!1)return null}let c=a?await a.fn(t):null,l=!a||a.executeMainFn?await(await TH(e)).deleteMany({model:i,where:t}):c;for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.after;r&&await OH(async()=>{await n(`db delete.after ${i}`,{[ve]:`delete.after`,[Ce]:i,[be]:t},()=>r(e,o))})}return l}async function l(t,i,a,o){let s=hH(),c=r.flatMap(({source:e,hooks:n})=>{let r=n[t]?.delete?.before;return r?[{source:e,fn:r}]:[]}),l=o??null;if(c.length){if(!l)try{l=(await(await TH(e)).findMany({model:t,where:i,limit:1}))[0]||null}catch{}if(l){for(let{source:e,fn:r}of c)if(await n(`db delete.before ${t}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":t,"better_auth.context":e},()=>r(l,s))===!1)return null}}let u=await a();if(!u)return null;for(let{source:e,hooks:i}of r){let r=i[t]?.delete?.after;r&&await OH(async()=>{await n(`db delete.after ${t}`,{[ve]:`delete.after`,[Ce]:t,[be]:e},()=>r(u,s))})}return u}return{createWithHooks:i,updateWithHooks:a,updateManyWithHooks:o,deleteWithHooks:s,deleteManyWithHooks:c,consumeOneWithHooks:l}}function rY(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}const iY=(e,t)=>{let n=t.logger,r=t.options,i=r.secondaryStorage,a=/* @__PURE__ */ new Map,o=r.session?.expiresIn||604800,s=!!i&&r.session?.storeSessionInDatabase===!0&&r.session?.preserveSessionInDatabase!==!0,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:u,deleteWithHooks:d,deleteManyWithHooks:f,consumeOneWithHooks:p}=nY(e,t),m=t=>{let n=[...t,{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}];return f(n,`session`,{fn:async()=>{await(await TH(e)).updateMany({model:`session`,where:n,update:{expiresAt:/* @__PURE__ */ new Date}})},executeMainFn:!1})};async function h(e){if(!i)return;let t=await i.get(`active-sessions-${e.id}`);if(!t)return;let n=Date.now(),r=(ye(t)||[]).filter(e=>e.expiresAt>n);await Promise.all(r.map(async({token:t})=>{let r=await i.get(t);if(!r)return;let a=ye(r);if(!a)return;let o=rY(a.session.expiresAt,n);await i.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function g(e){if(!i)return[];let t=await i.get(`active-sessions-${e}`);return t&&ye(t)||[]}async function _(e,t){if(!i)return;let n=new Set(t.map(e=>e.token));for(let{token:e}of t)await i.delete(e);let r=`active-sessions-${e}`,a=await g(e),o=Date.now(),s=a.filter(e=>e.expiresAt>o&&!n.has(e.token));s.sort((e,t)=>e.expiresAt-t.expiresAt);let c=s.at(-1)?.expiresAt;c?await i.set(r,JSON.stringify(s),rY(c,o)):await i.delete(r)}async function v(e,t){if(!i)return;let r=t??await g(e);await OH(()=>_(e,r),{onError(e){n.error(`Failed to delete committed user sessions from secondary storage`,e)}})}async function y(e,t){let n=a.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>i);a.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),a.get(e)===o&&a.delete(e)}}return{createOAuthUser:async(t,n)=>DH(e,async()=>{let e=await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...t,email:t.email?.toLowerCase()},`user`,void 0);if(!e)throw new E(`BAD_REQUEST`,{message:`Failed to create user`});return{user:e,account:await c({...n,userId:e.id,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date},`account`,void 0)}}),createUser:async(e,t)=>{let i={createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,email:e.email?.toLowerCase()};if(r.user?.validateUserInfo){let e={...t,action:`create-user`};ZJ(e);let r;try{r=gH()}catch(e){throw n.error(`Unable to run validateUserInfo: missing endpoint context`,e),new E(`FORBIDDEN`,{code:`validation_context_missing`,message:`User validation requires an endpoint context`})}await QJ(r,{user:i,source:e})}return await c(i,`user`,void 0)},createAccount:async e=>await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e},`account`,void 0),listSessions:async(n,r)=>{if(s)return(await(await TH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]})).map(e=>aG(t.options,e));if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=ye(e)||[],a=Date.now(),o=/* @__PURE__ */ new Set,s=[];for(let{token:e,expiresAt:n}of r){if(n<=a||o.has(e))continue;o.add(e);let r=await i.get(e);if(r)try{let e=typeof r==`string`?JSON.parse(r):r;if(!e?.session)continue;s.push(aG(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await TH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},...r?.onlyActiveSessions?[{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]:[]]})},listUsers:async(t,n,r,i)=>await(await TH(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await TH(e)).count({model:`user`,where:t});return typeof n==`string`?parseInt(n):n},deleteUser:async e=>{let t=await g(e);(!i||r.session?.storeSessionInDatabase)&&await f([{field:`userId`,value:e}],`session`,void 0),await f([{field:`userId`,value:e}],`account`,void 0),await d([{field:`id`,value:e}],`user`,void 0)!==null&&await v(e,t)},createSession:async(a,l,u,d,f)=>{let p=await(async()=>{let e=hH();return e?.headers||e?.request?.headers})(),m=r.session?.storeSessionInDatabase,h=f?.deferSecondaryStorageWrites===!0&&s,{id:g,..._}=u||{},v;if(i&&!m){let e=t.generateId({model:`session`});v=e===!1?ge():e}let y=dG(r),b={...v?{id:v}:{},ipAddress:p&&wJ(p,r)||``,userAgent:p?.get(`user-agent`)||``,..._,expiresAt:pG(l?86400:o,`sec`),userId:a,token:ge(32),createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...y,...d?_:{}},x=async t=>{if(!i)return t;let n=await i.get(`active-sessions-${a}`),r=[],o=Date.now();n&&(r=ye(n)||[],r=r.filter(e=>e.expiresAt>o&&e.token!==b.token));let s=[...r,{token:b.token,expiresAt:b.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=rY(s.at(-1)?.expiresAt??b.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await TH(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=rY(b.expiresAt,o);return u>0&&await i.set(b.token,JSON.stringify({session:t,user:l}),u),t};return await c(b,`session`,i?{fn:async e=>h?(await OH(async()=>{await x(e)},{onError(e){n.error(`Failed to mirror committed session to secondary storage`,e)}}),e):x(e),executeMainFn:m}:void 0)},findSession:async n=>{if(i){let e=await i.get(n);if(!e&&(!r.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let n=ye(e);return n?{session:aG(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:rG(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await TH(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:aG(t.options,s),user:rG(t.options,o)}:null},findSessions:async(t,n)=>{let r=[...new Set(t)],a=/* @__PURE__ */ new Map,o=[];if(i)for(let e of r){let t=await i.get(e);if(t)try{let r=typeof t==`string`?JSON.parse(t):t;if(!r)continue;let i=new Date(r.session.expiresAt);if(n?.onlyActiveSessions&&i<=/* @__PURE__ */ new Date)continue;let o={session:{...r.session,expiresAt:new Date(r.session.expiresAt)},user:{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)}};a.set(e,o)}catch{continue}else o.push(e)}let c=i?o:r;if(c.length>0&&(!i||s)){let t=await(await TH(e)).findMany({model:`session`,limit:c.length,where:[{field:`token`,value:c,operator:`in`},...n?.onlyActiveSessions?[{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]:[]],join:{user:!0}});for(let{user:e,...n}of t)e&&a.set(n.token,{session:n,user:e})}return r.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,n)=>await l(n,[{field:`token`,value:e}],`session`,i?{async fn(n){let r=await i.get(e);if(!r)return null;let a=ye(r);if(!a)return null;let o={...a.session,...n,expiresAt:new Date(n.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(n.updatedAt??a.session.updatedAt)},s=aG(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=rY(l,c);if(u>0){await i.set(e,JSON.stringify({session:s,user:a.user}),u);let t=`active-sessions-${s.userId}`,n=await i.get(t),r=(n&&ye(n)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=r.at(-1)?.expiresAt;o&&o>c?await i.set(t,JSON.stringify(r),rY(o,c)):await i.delete(t)}return s},executeMainFn:r.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(i){let a=await i.get(e);if(a){let{session:t}=ye(a)??{};if(!t){n.error(`Session not found in secondary storage`);return}let r=t.userId,o=await i.get(`active-sessions-${r}`);if(o){let t=ye(o)||[],n=Date.now(),a=t.filter(t=>t.expiresAt>n&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await i.set(`active-sessions-${r}`,JSON.stringify(a),rY(s,n)):await i.delete(`active-sessions-${r}`)}else n.error(`Active sessions list not found in secondary storage`)}if(await i.delete(e),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e}]);return}}await d([{field:`token`,value:e}],`session`,void 0)},deleteAccounts:async e=>{await f([{field:`userId`,value:e}],`account`,void 0)},deleteAccount:async e=>{await d([{field:`id`,value:e}],`account`,void 0)},deleteUserSessions:async e=>{let n=await g(e);if(i){if(!r.session?.storeSessionInDatabase){await v(e,n);return}if(t.options.session?.preserveSessionInDatabase){await m([{field:`userId`,value:e}])!==null&&await v(e,n);return}}await f([{field:`userId`,value:e}],`session`,void 0)!==null&&await v(e,n)},deleteSessions:async e=>{if(i){if(await Promise.all(e.map(e=>i.delete(e))),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e,operator:`in`}]);return}}await f([{field:`token`,value:e,operator:`in`}],`session`,void 0)},findAccountOwnerByKey:async({providerId:t,accountId:n})=>{let r=await(await TH(e)).findMany({model:`account`,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}],limit:2,join:{user:!0}});if(r.length>1)throw new D(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let i=r[0];if(!i)return null;let{user:a,...o}=i;return a?{kind:`owned`,user:a,account:o}:{kind:`orphaned`,account:o}},findUserByEmail:async(t,n)=>{let r=await(await TH(e)).findOne({model:`user`,where:[{value:t.toLowerCase(),field:`email`}],join:{...n?.includeAccounts?{account:!0}:{}}});if(!r)return null;let{account:i,...a}=r;return{user:a,accounts:i??[]}},findUserById:async t=>t?await(await TH(e)).findOne({model:`user`,where:[{field:`id`,value:t}]}):null,linkAccount:async e=>await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e},`account`,void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`id`,value:e}],`user`,void 0);return await OH(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`email`,value:e.toLowerCase()}],`user`,void 0);return await OH(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updatePassword:async(e,t)=>{await u({password:t},[{field:`userId`,value:e},{field:`providerId`,value:`credential`},{field:`accountId`,value:e}],`account`,void 0)},findAccounts:async t=>await(await TH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await TH(e)).findOne({model:`account`,where:[{field:`userId`,value:t},{field:`providerId`,value:`credential`},{field:`accountId`,value:t}]}),findAccountByKey:async({providerId:t,accountId:n})=>{let r=await(await TH(e)).findMany({model:`account`,limit:2,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}]});if(r.length>1)throw new D(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return r[0]??null},findAccountByUserId:async t=>await(await TH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:`id`,value:e}],`account`,void 0),createVerificationValue:async e=>{let t=tY(e.identifier,r.verification?.storeIdentifier),n=await eY(e.identifier,t);return await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=rY(e.expiresAt);return t>0&&await i.set(`verification:${n}`,JSON.stringify(e),t),e},executeMainFn:r.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let n=tY(t,r.verification?.storeIdentifier),a=await eY(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=ye(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=ye(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await TH(e);async function s(e){return o.findMany({model:`verification`,where:[{field:`identifier`,value:e}],sortBy:{field:`createdAt`,direction:`desc`},limit:1})}let c=await s(a);return!c.length&&n&&n!==`plain`&&(c=await s(t)),r.verification?.disableCleanup||await f([{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`lt`}],`verification`,void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await eY(e,tY(e,r.verification?.storeIdentifier));i&&await i.delete(`verification:${t}`),(!i||r.verification?.storeInDatabase)&&await d([{field:`identifier`,value:t}],`verification`,void 0)},consumeVerificationValue:async t=>{let n=tY(t,r.verification?.storeIdentifier),a=await eY(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?ye(e):typeof e==`object`?e:null;if(!t)return null;let n=new Date(t.expiresAt);return Number.isFinite(n.getTime())?{...t,expiresAt:n}:null},c=null;if(i&&!r.verification?.storeInDatabase){let e=async e=>s(await i.getAndDelete(e));for(let t of o){let n=await e(`verification:${t}`);if(n){await Promise.all(o.filter(e=>e!==t).map(e=>i.delete(`verification:${e}`))),c=n;break}}}else{let t=async t=>y(`verification:${t}`,()=>DH(e,async()=>{let n=await TH(e),r=[{field:`identifier`,value:t}],i=(await n.findMany({model:`verification`,where:r,sortBy:{field:`createdAt`,direction:`desc`},limit:1}))[0]??null;return i?p(`verification`,[{field:`id`,value:i.id}],async()=>{let e=await n.consumeOne({model:`verification`,where:[{field:`id`,value:i.id}]});return e?(await n.deleteMany({model:`verification`,where:r}),e):null},i):null}));for(let e of o)if(c=await t(e),c)break;c&&i&&await Promise.all(o.map(e=>i.delete(`verification:${e}`)))}return!c||c.expiresAt</* @__PURE__ */ new Date?null:c},reserveVerificationValue:async t=>{let n=we(new Uint8Array(await FU(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),r),a=tY(t.identifier,r.verification?.storeIdentifier),o=await eY(t.identifier,a);if(i&&!r.verification?.storeInDatabase)throw new D(`reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.`);try{await e.create({model:`verification`,data:{id:n,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:`verification`,where:[{field:`id`,value:n}]}))return!1;throw t}if(i){let e=rY(t.expiresAt);e>0&&await i.set(`verification:${o}`,JSON.stringify({id:n,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let n=await eY(e,tY(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=ye(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=rY(o instanceof Date?o:new Date(o));if(s>0&&await i.set(`verification:${n}`,JSON.stringify(e),s),!r.verification?.storeInDatabase)return e}}}return!i||r.verification?.storeInDatabase?await l(t,[{field:`identifier`,value:n}],`verification`,void 0):t},refreshUserSessions:h}};function aY(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function oY(e,t,n=`.`,r){if(!aY(t))return oY(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:aY(a)&&aY(i[t])?oY(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function sY(e){return(...t)=>t.reduce((t,n)=>oY(t,n,``,e),{})}const cY=sY(),lY=/* @__PURE__ */ new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function uY(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function dY(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function fY(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function pY(e){return e.replace(/\.+$/,``)}function mY(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function hY(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function gY(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function _Y(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=hY(e);return gY(t,hY(`127.0.0.0`),8)?`loopback`:gY(t,hY(`10.0.0.0`),8)||gY(t,hY(`172.16.0.0`),12)||gY(t,hY(`192.168.0.0`),16)?`private`:gY(t,hY(`169.254.0.0`),16)?`linkLocal`:gY(t,hY(`100.64.0.0`),10)?`sharedAddressSpace`:gY(t,hY(`192.0.2.0`),24)||gY(t,hY(`198.51.100.0`),24)||gY(t,hY(`203.0.113.0`),24)?`documentation`:gY(t,hY(`198.18.0.0`),15)?`benchmarking`:gY(t,hY(`224.0.0.0`),4)?`multicast`:gY(t,hY(`0.0.0.0`),8)||gY(t,hY(`192.0.0.0`),24)||gY(t,hY(`192.88.99.0`),24)||gY(t,hY(`240.0.0.0`),4)?`reserved`:`public`}function vY(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function yY(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=vY(e,1);return t&&_Y(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=vY(e,6);return t&&_Y(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=vY(e,6,{xor:!0});return t&&_Y(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function bY(e){let t=pY(fY(uY(dY(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!uJ(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:lY.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(mY(t))return{kind:_Y(t),literal:`ipv4`,canonical:t};let n=gJ(t,{ipv6Subnet:128});return mY(n)?{kind:_Y(n),literal:`ipv4`,canonical:n}:{kind:yY(n),literal:`ipv6`,canonical:n}}function xY(e){return bY(e).kind===`loopback`}function SY(e){let t=bY(e).kind;return t===`loopback`||t===`localhost`}function CY(e){return bY(e).kind===`public`}async function wY(e){let t=e.options,n=t.plugins||[],r=[],i=[];for(let a of n)if(a.init){let n=a.init(e),o;if(o=mG(n)?await n:n,typeof o==`object`){if(o.options){let{databaseHooks:e,trustedOrigins:n,...s}=o.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),n&&r.push(n),t=cY(t,s)}o.context&&Object.assign(e,o.context)}}if(r.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...r],n=e.filter(Array.isArray).flat(),i=e.filter(e=>typeof e==`function`);i.length>0?t.trustedOrigins=async e=>{let t=await Promise.all(i.map(t=>t(e)));return[...n,...t.flat()].filter(e=>typeof e==`string`&&e!==``)}:t.trustedOrigins=n}t.databaseHooks&&i.push({source:`user`,hooks:t.databaseHooks}),e.internalAdapter=iY(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function TY(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function EY(e,t){let n=[];if(WH(e.baseURL)){let t=e.baseURL.allowedHosts,r=e.baseURL.protocol;for(let e of t)e.includes(`://`)?n.push(e):((!r||r===`https`||r===`auto`)&&n.push(`https://${e}`),(r===`http`||r===`auto`||SY(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=BH(typeof e.baseURL==`string`?e.baseURL:void 0,e.basePath,t);r&&n.push(new URL(r).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&n.push(...e.trustedOrigins),typeof e.trustedOrigins==`function`)){let r=await e.trustedOrigins(t);n.push(...r)}let r=S.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function DY(e){if(GH(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has(`host`)||t.has(`x-forwarded-host`))return t}function OY(e){return e.advanced?.trustedProxyHeaders??!1}async function kY(e,t,n){let r=e.options.baseURL,i=XH(r,e.options.basePath||`/api/auth`,t,void 0,n);if(!i)throw new D(`Could not resolve base URL from request. Check your allowedHosts config.`);let a=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));a.baseURL=i,a.options={...e.options,baseURL:VH(i)||void 0};let o={...a.options,baseURL:r},s=typeof e.options.trustedOrigins==`function`||typeof e.options.account?.accountLinking?.trustedProviders==`function`,c;return c=s?GH(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await EY(o,c),a.trustedProviders=await jY(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=aq(a.options),a.createAuthCookie=iq(a.options)),a}async function AY(e,t){if(e)for(let n of e){let e=typeof n==`function`?await n():n;if(e[t.field??`id`]===t.value)return e}}async function jY(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function MY(e){return e}async function NY(e,t,n){let r={tokens:t,profile:n},i=e.accountSubject,a=await i(r),o=String(a);if(typeof a==`number`&&!Number.isFinite(a)||o.trim().length===0||o===`undefined`||o===`null`)throw new D(`OAUTH_ACCOUNT_SUBJECT_INVALID`);return{providerId:e.id,accountId:o}}async function PY(e,t,n){try{return await NY(e,t,n)}catch{throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO)}}function FY(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function IY(e,t){return e&&(t.options.account?.encryptOAuthTokens&&FY(e)?HW({key:t.secretConfig,data:e}):e)}function LY(e,t){return t.options.account?.encryptOAuthTokens&&e?VW({key:t.secretConfig,data:e}):e}function RY(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function zY(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}async function BY(e,t,n,r=3600,i){return await gU({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function VY(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,Y.VERIFICATION_EMAIL_NOT_ENABLED);let n=await BY(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:n},e.request)}const HY=X(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:A({email:Ve().meta({description:`The email to send the verification email to`}),callbackURL:k().meta({description:`The URL to use for email verification callback`}).optional()}),metadata:{openapi:{operationId:`sendVerificationEmail`,description:`Send a verification email to the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{email:{type:`string`,description:`The email to send the verification email to`,example:`user@example.com`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`,example:`https://example.com/callback`,nullable:!0}},required:[`email`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the email was sent successfully`,example:!0}}}}}},400:{description:`Bad Request`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`,description:`Error message`,example:`Verification email isn't enabled`}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,Y.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,n=await HJ(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await BY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await VY(e,r.user)}catch(e){i=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),i)throw i;return e.json({status:!0})}if(n?.user.email.toLowerCase()!==t.toLowerCase())throw E.from(`BAD_REQUEST`,Y.EMAIL_MISMATCH);if(n?.user.emailVerified)throw E.from(`BAD_REQUEST`,Y.EMAIL_ALREADY_VERIFIED);return await VY(e,n.user),e.json({status:!0})}),UY=X(`/verify-email`,{method:`GET`,operationId:`verifyEmail`,query:A({token:k().meta({description:`The token to verify the email`}),callbackURL:k().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[iJ(e=>e.query.callbackURL)],metadata:{openapi:{description:`Verify the email of the user`,parameters:[{name:`token`,in:`query`,description:`The token to verify the email`,required:!0,schema:{type:`string`}},{name:`callbackURL`,in:`query`,description:`The URL to redirect to after email verification`,required:!1,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the email was verified successfully`}},required:[`user`,`status`]}}}}}}}},async e=>{function t(t){if(e.query.callbackURL){let n=new URLSearchParams({error:t.code}),r=Cq(e.query.callbackURL,n);throw e.redirect(r)}throw E.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await $F(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof eP?t(Y.TOKEN_EXPIRED):t(Y.INVALID_TOKEN)}let i=A({email:Ve(),updateTo:k().optional(),requestType:k().optional()}).parse(r.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t(Y.USER_NOT_FOUND);if(i.updateTo){let n=await HJ(e);if(n&&n.user.email!==i.email)return t(Y.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await BY(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:r,token:t},zY(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case`change-email-verification`:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(r,e.request),await cq(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:rG(e.context.options,r)})}default:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await BY(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},zY(e.request))),await cq(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:rG(e.context.options,r)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await HJ(e);if(!t||t.user.email!==i.email){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);await cq(e,{session:t,user:{...a.user,emailVerified:!0}})}else await cq(e,{session:t.session,user:{...t.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function WY(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.trim().split(/\s+/).filter(Boolean):[]}function GY(e){let t=e=>new Date((/* @__PURE__ */ new Date()).getTime()+e*1e3);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:WY(e.scope),idToken:e.id_token,raw:e}}function KY(e,t){let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[],r=(t??[]).map(e=>e.trim()).filter(Boolean);return[.../* @__PURE__ */ new Set([...n,...r])].join(`,`)}function qY(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function JY(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return me.encode(new Uint8Array(n),{padding:!1})}const YY=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],XY=new Set(YY);async function ZY({id:e,options:t,authorizationEndpoint:n,state:r,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:u,responseType:d,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:_,scopeJoiner:v}){t=typeof t==`function`?await t():t;let y=new URL(t.authorizationEndpoint||n);y.searchParams.set(`response_type`,d||`code`);let b=qY(t.clientId);if(!b)throw Error(`OAuth provider requires clientId`);if(y.searchParams.set(`client_id`,b),y.searchParams.set(`state`,r),a?.length&&y.searchParams.set(`scope`,a.join(v||` `)),y.searchParams.set(`redirect_uri`,t.redirectURI||s),c&&y.searchParams.set(`duration`,c),f&&y.searchParams.set(`display`,f),p&&y.searchParams.set(`login_hint`,p),m&&y.searchParams.set(`nonce`,m),l&&y.searchParams.set(`prompt`,l),h&&y.searchParams.set(`hd`,h),u&&y.searchParams.set(`access_type`,u),g&&y.searchParams.set(`response_mode`,g),i){let e=await JY(i);y.searchParams.set(`code_challenge_method`,`S256`),y.searchParams.set(`code_challenge`,e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});y.searchParams.set(`claims`,JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(_)for(let[e,t]of Object.entries(_))XY.has(e)||y.searchParams.set(e,t);return y}const QY=ze(k(),k()).refine(e=>!Object.keys(e).some(e=>XY.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${YY.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional(),$Y=/^Basic +(.*)$/i;function eX(e){return new URLSearchParams({v:e}).toString().slice(2)}function tX(e){let t=new URLSearchParams(`v=${e}`).get(`v`);if(t===null)throw Error(`form-url-encoded value could not be decoded`);return t}function nX(e,t){let n=`${eX(e)}:${eX(t)}`;return`Basic ${he.encode(n)}`}function rX(e){let t=e.match($Y);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(he.decode(n)),i=r.indexOf(`:`);if(i===-1)throw Error(`Basic credential is missing the client id/secret separator`);let a=r.slice(0,i),o=r.slice(i+1);if(!a||!o)throw Error(`Basic credential client id and secret must both be non-empty`);return{clientId:tX(a),clientSecret:tX(o)}}const iX=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`];async function aX({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`}}var oX=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}};const sX=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}};var cX=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},lX=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function uX(e){if(typeof e==`number`)return new cX({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new cX(e);case`exponential`:return new lX(e);default:throw Error(`Invalid retry strategy`)}}const dX=[`get`,`post`,`put`,`patch`,`delete`];function fX(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return dX.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}const pX=e=>e===`.`||e===`..`,mX=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function hX(e,t){let n=t.get(e);if(n===void 0)return mX(e);if(pX(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function gX(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=fX(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=/* @__PURE__ */ new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>hX(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}const _X=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},vX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function yX(e){let t=e.headers.get(`content-type`),n=/* @__PURE__ */ new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return vX.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function bX(e){try{return JSON.parse(e),!0}catch{return!1}}function xX(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function SX(e){try{return JSON.parse(e)}catch{return e}}function CX(e){return typeof e==`function`}function wX(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&CX(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&CX(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function TX(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function EX(e){let t=new Headers(TX(e?.headers,await _X(e)));if(!t.has(`content-type`)){let n=DX(e?.body);n&&t.set(`content-type`,n)}return t}function DX(e){return xX(e)?`application/json`:null}function OX(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function kX(e,t){let{body:n}=e;return n?!xX(n)||typeof n==`string`?n:OX(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function AX(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=fX(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function jX(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var MX=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function NX(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new MX(n.issues);return n.value}function PX(e){"@babel/helpers - typeof";return PX=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},PX(e)}function FX(e,t){if(PX(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(PX(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function IX(e){var t=FX(e,`string`);return PX(t)==`symbol`?t:t+``}function LX(e,t,n){return(t=IX(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RX(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function zX(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?RX(Object(n),!0).forEach(function(t){LX(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RX(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const BX=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await sX(e,t),o=wX(a),s=new AbortController,c=a.signal??s.signal,l=gX(i,a),u=await EX(a),d=kX(a,u),f=AX(i,a),p=zX(zX({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=jX(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(zX(zX({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=yX(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??SX)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await NX(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(zX(zX({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??SX,b=await h.text(),x=bX(b),S=x?await y(b):null,ee={response:h,responseText:b,request:p,error:zX(zX({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var C;await e(zX(zX({},ee),{},{response:t!=null&&(C=t.hookOptions)!=null&&C.cloneResponse?h.clone():h}))}if(t?.retry){let n=uX(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await BX(e,zX(zX({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new oX(h.status,h.statusText,x?S:b);return{data:null,error:zX(zX({},S),{},{status:h.status,statusText:h.statusText})}},VX=/* @__PURE__ */ new Set([301,302,303,307,308]);function HX(e){return e.type===`opaqueredirect`||VX.has(e.status)}function UX(e){return new D(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function WX(e,t){let n=!1,r=t?.onError,i=await BX(e,{...t,redirect:`manual`,async onError(e){HX(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?UX(e):t});if(n)throw UX(e);return i}function GX(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function KX(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function qX(e,t){t&&e.set(`client_id`,t)}function JX(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function YX(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function XX({body:e,options:t,clientId:n,requireClientSecret:r}){r&&JX(`client_secret_post`,t),t.clientSecret&&(YX(`client_secret_post`,n),qX(e,n),e.set(`client_secret`,t.clientSecret))}function ZX({headers:e,options:t,clientId:n,body:r}){if(r.has(`client_secret`))throw Error(`client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters`);JX(`client_secret_basic`,t),YX(`client_secret_basic`,n),e.authorization=nX(n,t.clientSecret)}function QX(e){if(e.has(`client_assertion`)!==e.has(`client_assertion_type`))throw Error(`client_assertion and client_assertion_type must both be provided`)}async function $X({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){QX(e);let s=qY(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);KX(`private_key_jwt`,n,e),qX(e,s);return}let c=a??GX(n,o);if(c.method===`custom`)await c.customizeRequest({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i}),QX(e);else if(c.method===`private_key_jwt`){if(KX(c.method,n,e),YX(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await aX({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});qX(e,s);for(let[n,r]of Object.entries(t))e.set(n,r)}else if(c.method===`none`){if(KX(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);YX(c.method,s),qX(e,s)}else c.method===`client_secret_basic`?ZX({headers:t,options:n,clientId:s,body:e}):XX({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}const eZ=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],tZ=/* @__PURE__ */ new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function nZ(e){return{reserve:({key:t,expiresAt:n})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:n})}}function rZ(e,t){return Object.assign(Error(t),{code:e})}function iZ(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function aZ(e){if(!e)return;let t=e.trim();if(!t)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!n)return{scheme:`Unknown`,token:t};let r=n[1]??``,i=n[2]?.trim()??``;return r.toLowerCase()===`bearer`?{scheme:`Bearer`,token:i}:r.toLowerCase()===`dpop`?{scheme:`DPoP`,token:i}:{scheme:`Unknown`,token:t}}function oZ(e){return aZ(e)?.token??e}function sZ(e){let t=new URL(e);if(t.hash)throw Error(`DPoP proof htu must not contain a fragment`);return`${t.origin}${t.pathname}`}async function cZ(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return mP(new Uint8Array(t))}async function lZ(e){return oI(e,`sha256`)}function uZ(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.jkt;return typeof t==`string`&&t.length>0?t:void 0}function dZ(e){return uZ(e.cnf)}function fZ(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function pZ(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function mZ(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw rZ(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw rZ(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function hZ(e){if(!e||typeof e!=`object`||Array.isArray(e))throw rZ(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw rZ(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of tZ)if(t in e)throw rZ(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function gZ(e){let t=`${e.jkt}\n${e.htm}\n${e.htu}\n${e.jti}`,n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return mP(new Uint8Array(n))}async function _Z(e,t){if(e&&!await e.reserve(t))throw rZ(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function vZ({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=300,signingAlgorithms:c=eZ,replayStore:l}){if(!e||e.split(`.`).length!==3)throw rZ(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=pI(e)}catch(e){throw rZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw rZ(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);mZ(u.alg,c),hZ(u.jwk);let d;try{d=(await $F(e,await fI(u.jwk,u.alg),{typ:`dpop+jwt`})).payload}catch(e){throw rZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=fZ(d,`htm`),p=fZ(d,`htu`),m=fZ(d,`jti`),h=pZ(d,`iat`);if(!f||!p||!m||h===void 0)throw rZ(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>512)throw rZ(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw rZ(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=sZ(n),_=sZ(p)}catch(e){throw rZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw rZ(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw rZ(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=fZ(d,`ath`);if(a&&!v)throw rZ(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await cZ(r))throw rZ(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await lZ(u.jwk);if(i!==void 0&&y!==i)throw rZ(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await gZ({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=/* @__PURE__ */ new Date((h+s)*1e3);return await _Z(l,{key:b,expiresAt:x,now:/* @__PURE__ */ new Date(o*1e3)}),{jwk:u.jwk,jkt:y,jti:m,htm:f,htu:g,iat:h,ath:v,replayKey:b,expiresAt:x}}function yZ(e,t){return Object.assign(Error(t),{code:e})}function bZ(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function xZ({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=dZ(e);if(c){if(t.scheme!==`DPoP`)throw yZ(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw yZ(`invalid_dpop_proof`,`DPoP proof header is required`);try{await vZ({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw iZ(e)?yZ(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw yZ(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}const SZ=/* @__PURE__ */ new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function CZ({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=TZ({refreshToken:e,options:t,extraParams:a,resource:o});return await $X({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function wZ(e,t){if(t)for(let[n,r]of Object.entries(t))SZ.has(n)||e.set(n,r)}function TZ({refreshToken:e,options:t,extraParams:n,resource:r}){let i=new URLSearchParams,a={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`};if(i.set(`grant_type`,`refresh_token`),i.set(`refresh_token`,e),r){if(typeof r==`string`)i.append(`resource`,r);else for(let e of r)i.append(`resource`,e)}return n&&wZ(i,n),{body:i,headers:a}}async function EZ({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await CZ({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await WX(n,{method:`POST`,body:s,headers:c});if(u)throw u;let d={accessToken:l.access_token,refreshToken:l.refresh_token,tokenType:l.token_type,scopes:WY(l.scope),idToken:l.id_token};return l.expires_in&&(d.accessTokenExpiresAt=new Date((/* @__PURE__ */ new Date()).getTime()+l.expires_in*1e3)),l.refresh_token_expires_in&&(d.refreshTokenExpiresAt=new Date((/* @__PURE__ */ new Date()).getTime()+l.refresh_token_expires_in*1e3)),d}dP.code,cP.code,uP.code;const DZ=/* @__PURE__ */ new Map,OZ=/* @__PURE__ */ new WeakMap,kZ=5e3;function AZ(e,t){let n=e.get(t);return n||(n={fetchedAt:0,refetchedAt:0},e.set(t,n)),n}function jZ(e,t){return e.pending!==void 0&&t-e.pending.startedAt<kZ}async function MZ(e,t){let n=Date.now();if(!e.pending||!jZ(e,n)){let r={startedAt:n,promise:PZ(t).then(t=>(n>=e.fetchedAt&&(e.jwks=t,e.fetchedAt=n),t)).finally(()=>{e.pending===r&&(e.pending=void 0)})};e.pending=r}let{promise:r,startedAt:i}=e.pending,a;try{return await Promise.race([r,new Promise((e,t)=>{a=setTimeout(()=>t(new dP),i+kZ-n)})])}finally{clearTimeout(a)}}async function NZ(e,t,n){if(e.jwks!==t)return e.jwks;let r=Date.now();if(!jZ(e,r)){if(r-e.refetchedAt<3e4)return;e.refetchedAt=r}return MZ(e,n)}async function PZ(e){try{let t=typeof e==`string`?await WX(e,{headers:{Accept:`application/json`}}).then(async e=>{if(e.error)throw Error(`Jwks failed: ${e.error.message??e.error.statusText}`);return e.data}):await e();if(!t)throw Error(`No jwks found`);return t}catch(e){if(e instanceof TypeError){try{C.error(`JWKS fetch failed:`,e)}catch{}throw Error(`JWKS fetch failed`)}throw e}}async function FZ(e,t){return(await IZ(e,t)).jwks}async function IZ(e,t){let n;try{n=pI(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid,i=typeof t.jwksFetch==`string`?AZ(DZ,t.jwksFetch):t.jwksCacheKey?AZ(OZ,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},a=Date.now()-i.fetchedAt<3e5?i.jwks:void 0;if(!a)return{jwks:await MZ(i,t.jwksFetch),kid:r};let o=e=>NZ(i,e,t.jwksFetch);return!r||a.keys.some(e=>e.kid===r)?{jwks:a,kid:r,refresh:o}:{jwks:await o(a)??a,kid:r}}async function LZ({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:i,tokenEndpointAuth:a,tokenEndpoint:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){r=typeof r==`function`?await r():r;let d=Sfe({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await $X({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function Sfe({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:i,headers:a,additionalParams:o={},resource:s}){let c=new URLSearchParams,l={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`,...a};if(c.set(`grant_type`,`authorization_code`),c.set(`code`,e),t&&c.set(`code_verifier`,t),r.clientKey&&c.set(`client_key`,r.clientKey),i&&c.set(`device_id`,i),c.set(`redirect_uri`,r.redirectURI||n),s){if(typeof s==`string`)c.append(`resource`,s);else for(let e of s)c.append(`resource`,e)}for(let[e,t]of Object.entries(o))c.has(e)||c.append(e,t);return{body:c,headers:l}}async function RZ({code:e,codeVerifier:t,redirectURI:n,options:r,tokenEndpoint:i,authentication:a,tokenEndpointAuth:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){let{body:d,headers:f}=await LZ({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:a,tokenEndpointAuth:o,tokenEndpoint:i,deviceId:s,headers:c,additionalParams:l,resource:u}),{data:p,error:m}=await WX(i,{method:`POST`,body:d,headers:f});if(m)throw m;return GY(p)}const Cfe=[`iss`,`sub`,`aud`,`exp`,`iat`];function wfe(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:Cfe,clockTolerance:30}}async function Tfe(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Efe(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await Tfe(t):!1}async function Dfe(e,t,n){if(![t.audience].flat().some(Boolean))throw Error(`ID token audience is not configured`);let r=await $F(e,t.jwks,wfe(t));if(n&&!await Efe(r.payload.nonce,n,t.nonceComparison))throw Error(`ID token nonce does not match`);if(t.verifyClaims&&!t.verifyClaims(r.payload))throw Error(`ID token claims were rejected`);return r}function zZ(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function BZ(e,t,n,r){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,n,r);let a=e.idToken;return a?`verify`in a?await a.verify(t,n,r):t.split(`.`).length===3?(await Dfe(t,a,n),!0):a.allowOpaqueToken===!0:!1}catch{return!1}}function VZ(e,t){return{linked:!1,error:{code:e,message:t}}}async function Ofe(e,{link:t,userInfo:n,account:r,profile:i,scopes:a}){try{await QJ(e,{user:{...n,id:t.userId,email:n.email??void 0},source:{action:`link-account`,method:`oauth`,oauth:{providerId:r.providerId,profile:i}}})}catch(e){if(!Rq(e)||!e.body?.code)throw e;return VZ(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(r.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error(`Unable to link account - untrusted provider`),VZ(Tq.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return VZ(Tq.EMAIL_DOES_NOT_MATCH);let o=await e.context.internalAdapter.findAccountByKey(r);if(o){if(o.userId.toString()!==t.userId.toString())return VZ(Tq.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=KY(o.scope,a),i=Object.fromEntries(Object.entries({providerId:r.providerId,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:n||void 0}).filter(([e,t])=>t!==void 0));await e.context.internalAdapter.updateAccount(o.id,i)}else if(!await e.context.internalAdapter.createAccount({userId:t.userId,...r,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),scope:a?.join(`,`)??r.scope}))return VZ(Tq.UNABLE_TO_LINK_ACCOUNT);return await WZ(e,t.userId,n),{linked:!0}}async function HZ(e,t){let{userInfo:n,account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=t.source??{method:`oauth`,oauth:{providerId:r.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,l=null,u=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error(`Better auth was unable to query your database.
|
|
60
|
+
Error: `,t),Eq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)});if(u?.kind===`orphaned`)return e.context.logger.error(`OAuth account references a missing user. Repair the account before retrying authentication.`),{error:`unable to link account`,data:null,isRegister:!1};let d=await(async()=>{if(u?.kind===`owned`){if(t.selectedUser&&u.user.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`account_ownership_conflict`,message:`Account is already linked to another user`});return{user:u.user,linkedAccount:u.account,accounts:[u.account]}}if(t.selectedUser){let n=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!n)throw new E(`NOT_FOUND`,{code:`user_not_found`,message:`User not found`});return{user:n,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if(Rq(t))throw t;e.context.logger.error(`Better auth was unable to query your database.
|
|
61
|
+
Error: `,t),Eq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)}),f=d?.user,m=!f;if(d){let i=d.linkedAccount??d.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await QJ(e,{user:{...o,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`sign-in`}});let u=e.context.options.account?.updateAccountOnSignIn===!1?{}:Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>t!==void 0));if(e.context.options.account?.storeAccountCookie){let n={...i,...u};t.deferNonDatabaseWrites?l=n:await ZK(e,n)}if(Object.keys(u).length>0){let n=await e.context.internalAdapter.updateAccount(i.id,u);if(!n)return{error:`unable to update account`,data:null};if(c&&(n.accountId!==r.accountId||n.providerId!==r.providerId||n.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});t.deferNonDatabaseWrites&&l&&(l=n)}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||t.trustProviderByName!==!1&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!d.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return p()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:`account not linked`,data:null};try{let{id:i,...a}=n;await QJ(e,{user:{...a,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`link-account`}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:d.user.id,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:`unable to link account`,data:null};if(c&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=o:await ZK(e,o))}catch(t){if(Rq(t))throw t;return e.context.logger.error(`Unable to link account`,t),{error:`unable to link account`,data:null}}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0}),t.selectedUser||(f=await WZ(e,d.user.id,n)??f)}if(t.selectedUser?t.selectedUser.profile===`update`:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...c}=n,l=lG(e.context.options,c,`update`),u=await e.context.internalAdapter.updateUser(d.user.id,{name:o,image:s,...l,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===d.user.email&&d.user.emailVerified||n.emailVerified});if(u??e.context.logger.warn(`Could not update user info during OAuth sign in; preserving existing user for session.`),t.selectedUser&&u&&u.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`user_hook_selection_conflict`,message:`User hook changed the selected user`});f=u??f}}else{if(a)return{error:`signup disabled`,data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:u,image:d,...p}=n,m=lG(e.context.options,p,`create`),h={accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},{createdUser:g,createdAccount:_}=await DH(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:u,image:d,...m,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...h,userId:t.id})}});if(c&&(_.accountId!==r.accountId||_.providerId!==r.providerId||_.userId!==g.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});f=g,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=_:await ZK(e,_))}catch(t){if(Rq(t))throw t;return e.context.logger.error(`Unable to create OAuth user`,t),{error:`unable to create user`,data:null,isRegister:!1}}}if(!f)return{error:`unable to create user`,data:null,isRegister:!1};let h=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(m&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??h)&&await UZ(e,f,i,t.deferNonDatabaseWrites),h&&!f.emailVerified)return!m&&e.context.options.emailVerification?.sendOnSignIn&&await UZ(e,f,i,t.deferNonDatabaseWrites),{error:Tq.EMAIL_NOT_VERIFIED,data:null,isRegister:m};let g=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:t.deferNonDatabaseWrites===!0});if(!g)return{error:`unable to create session`,data:null,isRegister:!1};if(c&&g.userId!==(t.selectedUser?.userId??f.id))throw new E(`CONFLICT`,{code:`session_hook_user_conflict`,message:`Session hook changed the selected user`});return{data:{session:g,user:f},error:null,isRegister:m,accountCookie:l}}async function UZ(e,t,n,r){let i=e.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let a=async()=>{try{let r=await BY(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(n||`/`)}`;await e.context.runInBackgroundOrAwait(i({user:t,url:a,token:r},e.request))}catch(t){e.context.logger.error(`Failed to send OAuth verification email`,t)}};r?await OH(a):await a()}async function WZ(e,t,n){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:r,emailVerified:i,name:a,image:o,...s}=n,c=lG(e.context.options,s,`update`);return await e.context.internalAdapter.updateUser(t,{name:a,image:o,...c})}catch(t){e.context.logger.warn(`Could not update user info on account link`,t);return}}const kfe=e=>{let t=`https://appleid.apple.com/auth/token`;return{id:`apple`,name:`Apple`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i,codeVerifier:a}){if(!qY(e.clientId)||!e.clientSecret)throw C.error(`Client ID and client secret are required for Apple. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`name`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`apple`,options:e,authorizationEndpoint:`https://appleid.apple.com/auth/authorize`,scopes:o,state:t,redirectURI:r,codeVerifier:a,responseMode:`form_post`,responseType:`code id_token`,additionalParams:i})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),idToken:{jwks:e=>Afe(e.kid),issuer:`https://appleid.apple.com`,algorithms:[`RS256`],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:`1h`,nonceComparison:`exact-or-sha256`},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:e,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=mI(t.idToken);if(!n)return null;let r;r=t.user?.name?`${t.user.name.firstName||``} ${t.user.name.lastName||``}`.trim():n.name||``;let i=typeof n.email_verified==`boolean`?n.email_verified:n.email_verified===`true`,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},Afe=async e=>{let{data:t}=await BX(`https://appleid.apple.com/auth/keys`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await fI(n,n.alg)},jfe=e=>{let t=`https://auth.atlassian.com/oauth/token`;return{id:`atlassian`,name:`Atlassian`,accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw C.error(`Client Id and Secret are required for Atlassian`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Atlassian`);let o=e.disableDefaultScope?[]:[`read:jira-user`,`offline_access`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`atlassian`,options:e,authorizationEndpoint:`https://auth.atlassian.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:{...a??{},audience:`api.atlassian.com`},prompt:e.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:n}=await BX(`https://api.atlassian.com/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}catch(e){return C.error(`Failed to fetch user info from Atlassian:`,e),null}},options:e}},GZ=`https://dash.cloudflare.com/oauth2/token`,KZ=e=>{let t=e.clientSecret?`client_secret_basic`:`none`;return{method:e.tokenEndpointAuthMethod??t}},Mfe=e=>({id:`cloudflare`,name:`Cloudflare`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i}){let a=e.disableDefaultScope?[]:[`user-details.read`];return e.scope?.length&&a.push(...e.scope),n?.length&&a.push(...n),ZY({id:`cloudflare`,options:e,authorizationEndpoint:`https://dash.cloudflare.com/oauth2/auth`,scopes:a.length?[...new Set(a)]:void 0,state:t,codeVerifier:r,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>RZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:GZ,tokenEndpointAuth:KZ(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:GZ,tokenEndpointAuth:KZ(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.cloudflare.com/client/v4/user`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n?.success||!n.result)return C.error(`Failed to fetch user info from Cloudflare:`,r??n?.errors),null;let i=n.result,a=[i.first_name,i.last_name].filter(Boolean).join(` `)||i.email,o=await e.mapProfileToUser?.(i);return{user:{name:a,email:i.email,emailVerified:!1,...o},data:i}},options:e}),Nfe=e=>{if(!e.domain||!e.region||!e.userPoolId)throw C.error(`Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options.`),new D(`DOMAIN_AND_REGION_REQUIRED`);let t=e.domain.replace(/^https?:\/\//,``),n=`https://${t}/oauth2/authorize`,r=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:`cognito`,name:`Cognito`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!qY(e.clientId))throw C.error(`ClientId is required for Amazon Cognito. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(e.requireClientSecret&&!e.clientSecret)throw C.error(`Client Secret is required when requireClientSecret is true. Make sure to provide it in the options.`),new D(`CLIENT_SECRET_REQUIRED`);let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];e.scope&&s.push(...e.scope),r&&s.push(...r);let c=await ZY({id:`cognito`,options:{...e},authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...o??{}}}),l=c.searchParams.get(`scope`);if(l){c.searchParams.delete(`scope`);let e=encodeURIComponent(l),t=c.toString(),n=t.includes(`?`)?`&`:`?`;return new URL(`${t}${n}scope=${e}`)}return c},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>RZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),idToken:{jwks:t=>Pfe(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:[`RS256`],maxTokenAge:`1h`},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let n=mI(t.idToken);if(!n)return null;let r=n.name||n.given_name||n.username||``,i={...n,name:r},a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:i}}catch(e){C.error(`Failed to decode ID token:`,e)}if(t.accessToken)try{let{data:n}=await BX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n){let t=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.given_name||n.username||``,email:n.email,image:n.picture,emailVerified:n.email_verified,...t},data:n}}}catch(e){C.error(`Failed to fetch user info from Cognito:`,e)}return null},options:e}},Pfe=async(e,t,n)=>{let r=`https://cognito-idp.${t}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:t}=await BX(r);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await fI(n,n.alg)}catch(e){throw C.error(`Failed to fetch Cognito public key:`,e),e}},Ffe=e=>{let t=`https://discord.com/api/oauth2/token`;return{id:`discord`,name:`Discord`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identify`,`email`];n&&a.push(...n),e.scope&&a.push(...e.scope);let o=a.includes(`bot`);return ZY({id:`discord`,options:e,authorizationEndpoint:`https://discord.com/api/oauth2/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`none`,additionalParams:{...o&&e.permissions!==void 0?{permissions:String(e.permissions)}:{},...i??{}}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://discord.com/api/users/@me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;if(n.avatar===null)n.image_url=`https://cdn.discordapp.com/embed/avatars/${n.discriminator===`0`?Number(BigInt(n.id)>>BigInt(22))%6:parseInt(n.discriminator)%5}.png`;else{let e=n.avatar.startsWith(`a_`)?`gif`:`png`;n.image_url=`https://cdn.discordapp.com/avatars/${n.id}/${n.avatar}.${e}`}let i=await e.mapProfileToUser?.(n);return{user:{name:n.global_name||n.username||``,email:n.email,emailVerified:n.verified,image:n.image_url,...i},data:n}},options:e}},Ife=e=>{let t=`https://api.dropboxapi.com/oauth2/token`;return{id:`dropbox`,name:`Dropbox`,accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`account_info.read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`dropbox`,options:e,authorizationEndpoint:`https://www.dropbox.com/oauth2/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>await RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.dropboxapi.com/2/users/get_current_account`,{method:`POST`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...i},data:n}},options:e}};async function qZ(e,t){let n=qY(t.clientId);if(!n||!t.clientSecret)return null;let r=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await BX(`https://graph.facebook.com/debug_token`,{query:{input_token:e,access_token:`${n}|${t.clientSecret}`}});if(a||!i?.data)return null;let{is_valid:o,app_id:s,user_id:c}=i.data;return o!==!0||!s||!r.includes(s)||!c?null:c}const Lfe=e=>({id:`facebook`,name:`Facebook`,accountSubject:({profile:e})=>`sub`in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a}){if(!qY(e.clientId)||!e.clientSecret)throw C.error(`Client ID and client secret are required for Facebook. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`public_profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`facebook`,options:e,authorizationEndpoint:`https://www.facebook.com/v24.0/dialog/oauth`,scopes:o,state:t,redirectURI:r,loginHint:i,additionalParams:{...e.configId?{config_id:e.configId}:{},...a??{}}})},validateAuthorizationCode:async({code:t,redirectURI:n})=>RZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),idToken:{jwks:Hde(new URL(`https://limited.facebook.com/.well-known/oauth/openid/jwks/`)),issuer:`https://www.facebook.com`,audience:e.clientId,algorithms:[`RS256`],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),async getUserInfo(t){if(e.getUserInfo){let n=!!t.idToken&&t.idToken.split(`.`).length!==3,r=t.accessToken||(n?t.idToken:void 0);return r&&!await qZ(r,e)?null:e.getUserInfo(t)}if(t.idToken&&t.idToken.split(`.`).length===3){let n=mI(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}let n=t.accessToken;if(!n)return null;let r=await qZ(n,e);if(!r)return null;let{data:i,error:a}=await BX(`https://graph.facebook.com/me?fields=`+[`id`,`name`,`email`,`picture`,...e?.fields||[]].join(`,`),{auth:{type:`Bearer`,token:n}});if(a||i.id!==r)return null;let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...o},data:i}},options:e}),Rfe=e=>{let t=`https://api.figma.com/v1/oauth/token`;return{id:`figma`,name:`Figma`,accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw C.error(`Client Id and Client Secret are required for Figma. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Figma`);let o=e.disableDefaultScope?[]:[`current_user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`figma`,options:e,authorizationEndpoint:`https://www.figma.com/oauth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await BX(`https://api.figma.com/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return C.error(`Failed to fetch user from Figma`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.handle,email:n.email,image:n.img_url,emailVerified:!1,...r},data:n}}catch(e){return C.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},zfe=e=>{let t=`https://github.com/login/oauth/access_token`;return{id:`github`,name:`GitHub`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`read:user`,`user:email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),ZY({id:`github`,options:e,authorizationEndpoint:`https://github.com/login/oauth/authorize`,scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:r,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>{let{body:a,headers:o}=await LZ({code:n,codeVerifier:r,redirectURI:i,options:e}),{data:s,error:c}=await BX(t,{method:`POST`,body:a,headers:o});return c?(C.error(`GitHub OAuth token exchange failed:`,c),null):`error`in s?(C.error(`GitHub OAuth token exchange failed:`,s),null):GY(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.github.com/user`,{headers:{"User-Agent":`better-auth`,authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i}=await BX(`https://api.github.com/user/emails`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});!n.email&&i&&(n.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===n.email)?.verified??!1,o=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.login||``,email:n.email,image:n.avatar_url,emailVerified:a,...o},data:n}},options:e}},JZ=(e=``)=>e.split(`://`).map(e=>e.replace(/\/{2,}/g,`/`)).join(`://`),Bfe=e=>{let t=e||`https://gitlab.com`;return{authorizationEndpoint:JZ(`${t}/oauth/authorize`),tokenEndpoint:JZ(`${t}/oauth/token`),userinfoEndpoint:JZ(`${t}/api/v4/user`)}},Vfe=e=>{let{authorizationEndpoint:t,tokenEndpoint:n,userinfoEndpoint:r}=Bfe(e.issuer),i=`gitlab`;return{id:i,name:`Gitlab`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:n,scopes:r,codeVerifier:a,loginHint:o,redirectURI:s,additionalParams:c})=>{let l=e.disableDefaultScope?[]:[`read_user`];return e.scope&&l.push(...e.scope),r&&l.push(...r),await ZY({id:i,options:e,authorizationEndpoint:t,scopes:l,state:n,redirectURI:s,codeVerifier:a,loginHint:o,additionalParams:c})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>RZ({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:i}=await BX(r,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||n.state!==`active`||n.locked)return null;let a=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.username??``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...a},data:n}},options:e}},YZ=`RS256`,Hfe=[YZ],XZ=(e,t)=>e?typeof t!=`string`||!t?!1:e===`*`||t===e:!0,Ufe=e=>({id:`google`,name:`Google`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,display:o,additionalParams:s}){if(!qY(e.clientId)||!e.clientSecret)throw C.error(`Client Id and Client Secret is required for Google. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Google`);let c=e.disableDefaultScope?[]:[`email`,`profile`,`openid`];return e.scope&&c.push(...e.scope),n&&c.push(...n),await ZY({id:`google`,options:e,authorizationEndpoint:`https://accounts.google.com/o/oauth2/v2/auth`,scopes:c,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{...e.includeGrantedScopes===!1?{}:{include_granted_scopes:`true`},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>RZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://oauth2.googleapis.com/token`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://oauth2.googleapis.com/token`}),idToken:{jwks:e=>Wfe(e.kid),issuer:[`https://accounts.google.com`,`accounts.google.com`],audience:e.clientId,algorithms:Hfe,maxTokenAge:`1h`,verifyClaims:e.hd?t=>XZ(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=mI(t.idToken);if(!XZ(e.hd,n.hd))return C.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??`<missing>`}" does not satisfy the configured "hd" option "${e.hd}".`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...r},data:n}},options:e}),Wfe=async e=>{let[t]=await Gfe(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},Gfe=async e=>{let{data:t}=await BX(`https://www.googleapis.com/oauth2/v3/certs`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=e?t.keys.filter(t=>t.kid===e):t.keys;if(!n.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(n.map(e=>fI(e,YZ)))},Kfe=e=>{let t=`https://huggingface.co/oauth/token`;return{id:`huggingface`,name:`Hugging Face`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`huggingface`,options:e,authorizationEndpoint:`https://huggingface.co/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://huggingface.co/oauth/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},qfe=e=>{let t=`https://kauth.kakao.com/oauth/token`;return{id:`kakao`,name:`Kakao`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`account_email`,`profile_image`,`profile_nickname`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`kakao`,options:e,authorizationEndpoint:`https://kauth.kakao.com/oauth/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://kapi.kakao.com/v2/user/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n),a=n.kakao_account||{},o=a.profile||{};return{user:{name:o.nickname||a.name||``,email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:n}},options:e}},Jfe=e=>({id:`kick`,name:`Kick`,accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,codeVerifier:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`kick`,redirectURI:r,options:e,authorizationEndpoint:`https://id.kick.com/oauth/authorize`,scopes:o,codeVerifier:i,state:t,additionalParams:a})},async validateAuthorizationCode({code:t,redirectURI:n,codeVerifier:r}){return RZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://id.kick.com/oauth/token`,codeVerifier:r})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:`https://id.kick.com/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.kick.com/public/v1/users`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=n.data[0],a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),Yfe=e=>{let t=`https://api.line.me/oauth2/v2.1/token`;return{id:`line`,name:`LINE`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),await ZY({id:`line`,options:e,authorizationEndpoint:`https://access.line.me/oauth2/v2.1/authorize`,scopes:s,state:t,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,n)=>{let r=new URLSearchParams;r.set(`id_token`,t),r.set(`client_id`,e.clientId),n&&r.set(`nonce`,n);let{data:i,error:a}=await BX(`https://api.line.me/oauth2/v2.1/verify`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:r});return!(a||!i||i.aud!==e.clientId||i.nonce&&i.nonce!==n)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=null;if(t.idToken)try{n=mI(t.idToken)}catch{}if(!n){let{data:e}=await BX(`https://api.line.me/oauth2/v2.1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});n=e||null}if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}},options:e}},Xfe=e=>{let t=`https://api.linear.app/oauth/token`;return{id:`linear`,name:`Linear`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`linear`,options:e,authorizationEndpoint:`https://linear.app/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.linear.app/graphql`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
62
|
+
query {
|
|
63
|
+
viewer {
|
|
64
|
+
id
|
|
65
|
+
name
|
|
66
|
+
email
|
|
67
|
+
avatarUrl
|
|
68
|
+
active
|
|
69
|
+
createdAt
|
|
70
|
+
updatedAt
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
`})});if(r||!n?.data?.viewer)return null;let i=n.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{name:n.data.viewer.name,email:n.data.viewer.email,image:n.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},Zfe=e=>{let t=`https://www.linkedin.com/oauth/v2/accessToken`;return{id:`linkedin`,name:`Linkedin`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`profile`,`email`,`openid`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`linkedin`,options:e,authorizationEndpoint:`https://www.linkedin.com/oauth/v2/authorization`,scopes:o,state:t,loginHint:i,redirectURI:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>await RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.linkedin.com/v2/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,emailVerified:n.email_verified??!1,image:n.picture,...i},data:n}},options:e}},ZZ=`9188040d-6c67-4c5b-b112-36a304b66dad`,Qfe=e=>{let t=e.tenantId||`common`,n=e.authority||`https://login.microsoftonline.com`;for(;n.endsWith(`/`);)n=n.slice(0,-1);let r=`${n}/${t}/oauth2/v2.0/authorize`,i=`${n}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new D(`Microsoft Entra ID clientAssertion cannot be combined with clientSecret`);let a=e.clientAssertion?{method:`private_key_jwt`,getClientAssertion:e.clientAssertion}:void 0;return{id:`microsoft`,name:`Microsoft EntraID`,accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!qY(e.clientId))throw C.error(`Client Id is required for Microsoft Entra ID. Make sure to provide it in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),ZY({id:`microsoft`,options:e,authorizationEndpoint:r,state:t.state,codeVerifier:t.codeVerifier,scopes:n,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode({code:t,codeVerifier:n,redirectURI:r}){return RZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:i,tokenEndpointAuth:a})},idToken:{jwks:e=>$fe(e.kid,t,n),algorithms:[`RS256`],audience:e.clientId,maxTokenAge:`1h`,issuer:t!==`common`&&t!==`organizations`&&t!==`consumers`?`${n}/${t}/v2.0`:void 0,verifyClaims:e=>{let r=e.tid;return!(typeof r!=`string`||e.iss!==`${n}/${r}/v2.0`||t===`organizations`&&r===ZZ||t===`consumers`&&r!==ZZ)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=mI(t.idToken);if(typeof n.oid!=`string`||n.oid.trim().length===0)return C.error(`Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier.`),null;let r=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await BX(`https://graph.microsoft.com/v1.0/me/photos/${r}x${r}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer();n.picture=`data:image/jpeg;base64, ${he.encode(t)}`}catch(e){C.error(e&&typeof e==`object`&&`name`in e?e.name:``,e)}}});let i=await e.mapProfileToUser?.(n),a=n.email_verified===void 0?!!(n.email&&(n.verified_primary_email?.includes(n.email)||n.verified_secondary_email?.includes(n.email))):n.email_verified;return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:a,...i},data:n}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),EZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:n.join(` `)},tokenEndpoint:i,tokenEndpointAuth:a})},options:e}},$fe=async(e,t,n)=>{let{data:r}=await BX(`${n}/${t}/discovery/v2.0/keys`);if(!r?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let i=r.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await fI(i,i.alg??`RS256`)},epe=e=>{let t=`https://nid.naver.com/oauth2.0/token`;return{id:`naver`,name:`Naver`,accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`profile`,`email`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`naver`,options:e,authorizationEndpoint:`https://nid.naver.com/oauth2.0/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://openapi.naver.com/v1/nid/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n||n.resultcode!==`00`)return null;let i=await e.mapProfileToUser?.(n),a=n.response||{};return{user:{name:a.name||a.nickname||``,email:a.email,image:a.profile_image,emailVerified:!1,...i},data:n}},options:e}},tpe=e=>{let t=`https://api.notion.com/v1/oauth/token`;return{id:`notion`,name:`Notion`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=(e.disableDefaultScope,[]);return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`notion`,options:e,authorizationEndpoint:`https://api.notion.com/v1/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:{...a??{},owner:`user`}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.notion.com/v1/users/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":`2022-06-28`}});if(r||!n)return null;let i=n.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{name:i.name||``,email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},npe=e=>{let t=e.issuer||`https://idp.paybin.io`,n=`${t}/oauth2/authorize`,r=`${t}/oauth2/token`;return{id:`paybin`,name:`Paybin`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw C.error(`Client Id and Client Secret is required for Paybin. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new D(`codeVerifier is required for Paybin`);let c=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&c.push(...e.scope),r&&c.push(...r),await ZY({id:`paybin`,options:e,authorizationEndpoint:n,scopes:c,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>RZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=mI(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified||!1,...r},data:n}},options:e}},rpe=e=>{let t=(e.environment||`sandbox`)===`sandbox`,n=t?`https://www.sandbox.paypal.com/signin/authorize`:`https://www.paypal.com/signin/authorize`,r=t?`https://api-m.sandbox.paypal.com/v1/oauth2/token`:`https://api-m.paypal.com/v1/oauth2/token`,i=t?`https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo`:`https://api-m.paypal.com/v1/identity/oauth2/userinfo`,a={clientId:e.clientId,clientSecret:e.clientSecret},o={method:`client_secret_basic`};return{id:`paypal`,name:`PayPal`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw C.error(`Client Id and Client Secret is required for PayPal. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);return await ZY({id:`paypal`,options:e,authorizationEndpoint:n,scopes:[],state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>{try{return await RZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw C.error(`PayPal token exchange failed:`,e),new D(`FAILED_TO_GET_ACCESS_TOKEN`)}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await EZ({refreshToken:e,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw C.error(`PayPal token refresh failed:`,e),new D(`FAILED_TO_REFRESH_ACCESS_TOKEN`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return C.error(`Access token is required to fetch PayPal user info`),null;try{let n=await BX(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:`application/json`}});if(!n.data)return C.error(`Failed to fetch user info from PayPal`),null;let r=n.data;if(t.idToken){let e;try{e=mI(t.idToken).sub}catch(e){return C.error(`Failed to decode PayPal ID token:`,e),null}let n=r.sub??r.user_id;if(!e||n!==e)return C.error(`PayPal user info subject does not match ID token subject`),null}let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:r}}catch(e){return C.error(`Failed to fetch user info from PayPal:`,e),null}},options:e}},ipe=e=>{let t=`https://api.polar.sh/v1/oauth2/token`;return{id:`polar`,name:`Polar`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`polar`,options:e,authorizationEndpoint:`https://polar.sh/oauth2/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.polar.sh/v1/oauth2/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.public_name||n.username||``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},QZ=`https://backboard.railway.com/oauth/token`,ape=e=>({id:`railway`,name:`Railway`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`railway`,options:e,authorizationEndpoint:`https://backboard.railway.com/oauth/auth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>RZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:QZ,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:QZ,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://backboard.railway.com/oauth/me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}},options:e});function $Z({identifier:e,namespace:t}){let n=Ve().safeParse(`${e}@${t}.placeholder.invalid`);if(!n.success)throw TypeError(`Invalid placeholder email`);return n.data}const eQ={apple:kfe,atlassian:jfe,cloudflare:Mfe,cognito:Nfe,discord:Ffe,facebook:Lfe,figma:Rfe,github:zfe,microsoft:Qfe,google:Ufe,huggingface:Kfe,slack:e=>{let t=`https://slack.com/api/openid.connect.token`;return{id:`slack`,name:`Slack`,accountSubject:({profile:e})=>e[`https://slack.com/user_id`],createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return n&&a.push(...n),e.scope&&a.push(...e.scope),ZY({id:`slack`,options:e,authorizationEndpoint:`https://slack.com/openid/connect/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://slack.com/api/openid.connect.userInfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,emailVerified:n.email_verified,image:n.picture||n[`https://slack.com/user_image_512`],...i},data:n}},options:e}},spotify:e=>{let t=`https://accounts.spotify.com/api/token`;return{id:`spotify`,name:`Spotify`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user-read-email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`spotify`,options:e,authorizationEndpoint:`https://accounts.spotify.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.spotify.com/v1/me`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.display_name,email:n.email,image:n.images[0]?.url,emailVerified:!1,...i},data:n}},options:e}},twitch:e=>{let t=`https://id.twitch.tv/oauth2/token`;return{id:`twitch`,name:`Twitch`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user:read:email`,`openid`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`twitch`,redirectURI:r,options:e,authorizationEndpoint:`https://id.twitch.tv/oauth2/authorize`,scopes:a,state:t,claims:e.claims||[`email`,`email_verified`,`preferred_username`,`picture`],additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.idToken;if(!n)return C.error(`No idToken found in token`),null;let r=mI(n),i=await e.mapProfileToUser?.(r);return{user:{name:r.preferred_username,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}},twitter:e=>{let t=`https://api.x.com/2/oauth2/token`;return{id:`twitter`,name:`Twitter`,accountSubject:({profile:e})=>e.data.id,createAuthorizationURL(t){let n=e.disableDefaultScope?[]:[`users.read`,`tweet.read`,`offline.access`,`users.email`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),ZY({id:`twitter`,options:e,authorizationEndpoint:`https://x.com/i/oauth2/authorize`,scopes:n,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>RZ({code:n,codeVerifier:r,authentication:`basic`,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:`basic`,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.x.com/2/users/me?user.fields=profile_image_url`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i,error:a}=await BX(`https://api.x.com/2/users/me?user.fields=confirmed_email`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(n.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(n);return{user:{name:n.data.name,email:n.data.email||$Z({identifier:n.data.id,namespace:`twitter`}),image:n.data.profile_image_url,emailVerified:o,...s},data:n}},options:e}},dropbox:Ife,kick:Jfe,linear:Xfe,linkedin:Zfe,gitlab:Vfe,tiktok:e=>{let t=`https://open.tiktokapis.com/v2/oauth/token/`,n={method:`custom`,customizeRequest({body:t}){t.set(`client_key`,e.clientKey),t.set(`client_secret`,e.clientSecret)}};return{id:`tiktok`,name:`TikTok`,accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user.info.profile`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://www.tiktok.com/v2/auth/authorize`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`client_key`,e.clientKey),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),i)for(let[e,t]of Object.entries(i))XY.has(e)||e!==`client_key`&&o.searchParams.set(e,t);return o},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>RZ({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>EZ({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://open.tiktokapis.com/v2/user/info/?fields=${[`open_id`,`avatar_large_url`,`display_name`,`username`].join(`,`)}`,{headers:{authorization:`Bearer ${t.accessToken}`}});return r?null:{user:{email:n.data.user.email||$Z({identifier:n.data.user.open_id,namespace:`tiktok`}),name:n.data.user.display_name||n.data.user.username||``,image:n.data.user.avatar_large_url,emailVerified:!1},data:n}},options:e}},reddit:e=>{let t=`https://www.reddit.com/api/v1/access_token`,n={clientId:e.clientId,clientSecret:e.clientSecret},r={method:`client_secret_basic`};return{id:`reddit`,name:`Reddit`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identity`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`reddit`,options:e,authorizationEndpoint:`https://www.reddit.com/api/v1/authorize`,scopes:a,state:t,redirectURI:r,duration:e.duration,additionalParams:i})},validateAuthorizationCode:async({code:i,redirectURI:a})=>RZ({code:i,redirectURI:e.redirectURI||a,options:n,tokenEndpoint:t,tokenEndpointAuth:r,headers:{accept:`text/plain`,"user-agent":`better-auth`}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>EZ({refreshToken:e,options:n,tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://oauth.reddit.com/api/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});if(r)return null;let i=await e.mapProfileToUser?.(n),a=i?.email||$Z({identifier:n.id,namespace:`reddit`});return{user:{name:n.name,image:n.icon_img?.split(`?`)[0],...i,email:a,emailVerified:i?.emailVerified??!1},data:n}},options:e}},roblox:e=>{let t=`https://apis.roblox.com/oauth/v1/token`;return{id:`roblox`,name:`Roblox`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`roblox`,options:e,authorizationEndpoint:`https://apis.roblox.com/oauth/v1/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`select_account consent`,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>RZ({code:n,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t,authentication:`post`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://apis.roblox.com/oauth/v1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.nickname||n.preferred_username||``,image:n.picture,email:$Z({identifier:n.sub,namespace:`roblox`}),emailVerified:!1,...i},data:{...n}}},options:e}},salesforce:e=>{let t=(e.environment??`production`)===`sandbox`,n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?`https://test.salesforce.com/services/oauth2/authorize`:`https://login.salesforce.com/services/oauth2/authorize`,r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?`https://test.salesforce.com/services/oauth2/token`:`https://login.salesforce.com/services/oauth2/token`,i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?`https://test.salesforce.com/services/oauth2/userinfo`:`https://login.salesforce.com/services/oauth2/userinfo`;return{id:`salesforce`,name:`Salesforce`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw C.error(`Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new D(`codeVerifier is required for Salesforce`);let s=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&s.push(...e.scope),r&&s.push(...r),ZY({id:`salesforce`,options:e,authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:e.redirectURI||a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>RZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>EZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await BX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return C.error(`Failed to fetch user info from Salesforce`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.photos?.picture||n.photos?.thumbnail,emailVerified:n.email_verified??!1,...r},data:n}}catch(e){return C.error(`Failed to fetch user info from Salesforce:`,e),null}},options:e}},vk:e=>{let t=`https://id.vk.com/oauth2/auth`;return{id:`vk`,name:`VK`,accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`email`,`phone`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`vk`,options:e,authorizationEndpoint:`https://id.vk.com/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i,deviceId:a})=>RZ({code:n,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>EZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let{data:n,error:r}=await BX(`https://id.vk.com/oauth2/user_info`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString()});if(r)return null;let i=await e.mapProfileToUser?.(n);return!n.user.email&&!i?.email?null:{user:{first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...i},data:n}},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:`zoom`,name:`Zoom`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:n,codeVerifier:r,additionalParams:i})=>ZY({id:`zoom`,options:t,authorizationEndpoint:`https://zoom.us/oauth/authorize`,state:e,redirectURI:n,codeVerifier:t.pkce?r:void 0,additionalParams:i}),validateAuthorizationCode:async({code:e,redirectURI:n,codeVerifier:r})=>RZ({code:e,redirectURI:t.redirectURI||n,codeVerifier:r,options:t,tokenEndpoint:`https://zoom.us/oauth/token`,authentication:`post`}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>EZ({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:`https://zoom.us/oauth/token`}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:n,error:r}=await BX(`https://api.zoom.us/v2/users/me`,{headers:{authorization:`Bearer ${e.accessToken}`}});if(r)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.display_name,image:n.pic_url,email:n.email,emailVerified:!!n.verified,...i},data:{...n}}}}},notion:tpe,kakao:qfe,naver:epe,line:Yfe,paybin:npe,paypal:rpe,polar:ipe,railway:ape,vercel:e=>({id:`vercel`,name:`Vercel`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!r)throw new D(`codeVerifier is required for Vercel`);let o;return(e.scope!==void 0||n!==void 0)&&(o=[],e.scope&&o.push(...e.scope),n&&o.push(...n)),ZY({id:`vercel`,options:e,authorizationEndpoint:`https://vercel.com/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>RZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://api.vercel.com/login/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.vercel.com/login/oauth/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.preferred_username??``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}),wechat:e=>({id:`wechat`,name:`WeChat`,accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`snsapi_login`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://open.weixin.qq.com/connect/qrconnect`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`appid`,e.clientId),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),o.searchParams.set(`lang`,e.lang||`cn`),i)for(let[e,t]of Object.entries(i))XY.has(e)||e!==`appid`&&o.searchParams.set(e,t);return o.hash=`wechat_redirect`,o},validateAuthorizationCode:async({code:t})=>{let{data:n,error:r}=await BX(`https://api.weixin.qq.com/sns/oauth2/access_token?`+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:`authorization_code`}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to validate authorization code: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`),openid:n.openid,unionid:n.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:n,error:r}=await BX(`https://api.weixin.qq.com/sns/oauth2/refresh_token?`+new URLSearchParams({appid:e.clientId,grant_type:`refresh_token`,refresh_token:t}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to refresh access token: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.openid;if(!n)return null;let{data:r,error:i}=await BX(`https://api.weixin.qq.com/sns/userinfo?`+new URLSearchParams({access_token:t.accessToken||``,openid:n,lang:`zh_CN`}).toString(),{method:`GET`});if(i||!r||r.errcode)return null;let a=await e.mapProfileToUser?.(r),o=r.unionid||r.openid||n;return{user:{name:r.nickname,email:r.email||$Z({identifier:o,namespace:`wechat`}),image:r.headimgurl,emailVerified:!1,...a},data:r}},options:e})},ope=Object.keys(eQ),tQ=Ze(ope).or(k());function nQ(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const spe=X(`/list-accounts`,{method:`GET`,use:[WJ],metadata:{openapi:{operationId:`listUserAccounts`,description:`List all accounts linked to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},createdAt:{type:`string`,format:`date-time`},updatedAt:{type:`string`,format:`date-time`},accountId:{type:`string`},userId:{type:`string`},scopes:{type:`array`,items:{type:`string`}}},required:[`id`,`providerId`,`createdAt`,`updatedAt`,`accountId`,`userId`,`scopes`]}}}}}}}}},async e=>{let t=e.context.session,n=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(n.map(t=>{let{scope:n,...r}=oG(e.context.options,t);return{...r,scopes:nQ(n)}}))}),cpe=X(`/link-social`,{method:`POST`,requireHeaders:!0,body:A({callbackURL:k().meta({description:`The URL to redirect to after the user has signed in`}).optional(),provider:tQ,idToken:A({token:k(),nonce:k().optional(),accessToken:k().optional(),refreshToken:k().optional()}).optional(),requestSignUp:Je().optional(),scopes:Be(k()).meta({description:`Additional scopes to request from the provider`}).optional(),errorCallbackURL:k().meta({description:`The URL to redirect to if there is an error during the link process`}).optional(),disableRedirect:Je().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),loginHint:k().meta({description:`The login hint to use for the authorization code request`}).optional(),additionalParams:QY,additionalData:ze(k(),et()).optional()}),use:[WJ],metadata:{openapi:{description:`Link a social account to the user`,operationId:`linkSocialAccount`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{url:{type:`string`,description:`The authorization URL to redirect the user to`},redirect:{type:`boolean`,description:`Indicates if the user should be redirected to the authorization URL`},status:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=e.context.session,n=await AY(e.context.socialProviders,{value:e.body.provider});if(!n)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!zZ(n))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await BZ(n,r,i,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.INVALID_TOKEN);let a=await n.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(Dq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await PY(n,{idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},a.data),s=await e.context.internalAdapter.findAccountByKey(o);if(s?.userId===t.user.id){let i=Object.fromEntries(Object.entries({providerId:n.id,accessToken:await LY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await LY(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>t!==void 0));return await e.context.internalAdapter.updateAccount(s.id,i),await WZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}if(s)throw E.from(`CONFLICT`,Y.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(n.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - linking not allowed`,code:`LINKING_NOT_ALLOWED`});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - different emails not allowed`,code:`LINKING_DIFFERENT_EMAILS_NOT_ALLOWED`});try{await e.context.internalAdapter.createAccount({userId:t.user.id,...o,accessToken:await LY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await LY(e.body.idToken.refreshToken,e.context)})}catch{throw E.from(`EXPECTATION_FAILED`,{message:`Account not linked - unable to create account`,code:`LINKING_FAILED`})}return await WZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}let r=Pq(n),i=await Fq(e,{link:{userId:t.user.id,email:t.user.email},additionalData:e.body.additionalData,idTokenNonce:r}),a=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:r,redirectURI:`${e.context.baseURL}${RY(n)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),lpe=X(`/unlink-account`,{method:`POST`,body:A({accountId:k().meta({description:`The Better Auth account ID to unlink`})}),use:[KJ],metadata:{openapi:{description:`Unlink an account`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let{accountId:t}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(n.length===1&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_UNLINK_LAST_ACCOUNT);let r=n.find(e=>e.id===t);if(!r)throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(r.id),e.json({status:!0})});async function rQ(e,t){let n=await HJ(e,{disableCookieCache:VJ(e)});if(!n&&(e.request||e.headers))throw e.error(`UNAUTHORIZED`);let r=n?.user?.id||t;if(!r)throw E.from(`BAD_REQUEST`,{message:`Either userId or session is required`,code:`USER_ID_OR_SESSION_REQUIRED`});return r}const iQ=Ae([it({accountId:k().meta({description:`The Better Auth account ID`}),userId:k().meta({description:`The user ID associated with the account`}).optional()}),it({useAccountCookie:Ye(!0).meta({description:`Select the current OAuth account from its signed cookie`}),userId:k().meta({description:`The user ID associated with the account`}).optional()})]);function aQ(e,t,{resolvedUserId:n,selection:r}){return(!qW(e.context.options)||t.userId===n)&&(`accountId`in r?t.id===r.accountId:!0)}async function oQ(e,{resolvedUserId:t,selection:n}){if(`accountId`in n){let r=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===n.accountId);if(r)return{account:r,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let r=await QK(e);if(r&&aQ(e,r,{resolvedUserId:t,selection:n}))return{account:r,accountCookie:r}}throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND)}async function sQ(e,{resolvedUserId:t,selection:n,account:r}){let i=r??(await oQ(e,{resolvedUserId:t,selection:n})).account;if(!aQ(e,i,{resolvedUserId:t,selection:n}))throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);let a=await AY(e.context.socialProviders,{value:i.providerId});if(!a)throw E.from(`BAD_REQUEST`,{message:`Provider ${i.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});try{let t=null,n=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(i.refreshToken&&n&&a.refreshAccessToken){let n=await IY(i.refreshToken,e.context);t=await a.refreshAccessToken(n,e);let r={accessToken:await LY(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await LY(t.refreshToken,e.context):i.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:t?.idToken||i.idToken},o=null;i.id&&(o=await e.context.internalAdapter.updateAccount(i.id,r)),e.context.options.account?.storeAccountCookie&&await ZK(e,{...i,...o??r})}let r=(()=>{if(t?.accessTokenExpiresAt)return typeof t.accessTokenExpiresAt==`string`?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt;if(i.accessTokenExpiresAt)return typeof i.accessTokenExpiresAt==`string`?new Date(i.accessTokenExpiresAt):i.accessTokenExpiresAt})();return{accessToken:t?.accessToken??await IY(i.accessToken??``,e.context),accessTokenExpiresAt:r,scopes:nQ(i.scope),idToken:t?.idToken??i.idToken??void 0}}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to get a valid access token`,code:`FAILED_TO_GET_ACCESS_TOKEN`})}}const upe=X(`/get-access-token`,{method:`POST`,body:iQ,metadata:{openapi:{description:`Get a valid access token, doing a refresh if needed`,responses:{200:{description:`A Valid access token`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,n=await sQ(e,{resolvedUserId:await rQ(e,t),selection:e.body});return e.json(n)}),dpe=X(`/refresh-token`,{method:`POST`,body:iQ,metadata:{openapi:{description:`Refresh the access token using a refresh token`,responses:{200:{description:`Access token refreshed successfully`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},refreshToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`},refreshTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,{account:n,accountCookie:r}=await oQ(e,{resolvedUserId:await rQ(e,t),selection:e.body}),i=await AY(e.context.socialProviders,{value:n.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});if(!i.refreshAccessToken)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} does not support token refreshing.`,code:`TOKEN_REFRESH_NOT_SUPPORTED`});let a=n.refreshToken??void 0;if(!a)throw E.from(`BAD_REQUEST`,{message:`Refresh token not found`,code:`REFRESH_TOKEN_NOT_FOUND`});try{let t=await IY(a,e.context),o=await i.refreshAccessToken(t,e),s=o.refreshToken?await LY(o.refreshToken,e.context):a,c=o.refreshTokenExpiresAt??n.refreshTokenExpiresAt,l={accessToken:await LY(o.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,idToken:o.idToken||n.idToken},u=null;n.id&&(u=await e.context.internalAdapter.updateAccount(n.id,l)),r?.id===n.id&&e.context.options.account?.storeAccountCookie&&await ZK(e,{...r,...u??l});let d=u?.scope??n.scope;return e.json({accessToken:o.accessToken,refreshToken:o.refreshToken??t,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,scope:d,idToken:o.idToken||n.idToken,providerId:n.providerId,accountId:n.id})}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to refresh access token`,code:`FAILED_TO_REFRESH_ACCESS_TOKEN`})}}),fpe=X(`/account-info`,{method:`GET`,metadata:{openapi:{description:`Get the account info provided by the provider`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,properties:{name:{type:`string`},email:{type:`string`,nullable:!0},image:{type:`string`},emailVerified:{type:`boolean`}},required:[`emailVerified`]},account:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},accountId:{type:`string`}},required:[`id`,`providerId`,`accountId`],additionalProperties:!1},data:{type:`object`,properties:{},additionalProperties:!0}},required:[`user`,`data`,`account`],additionalProperties:!1}}}}}}},query:iQ},async e=>{let{userId:t}=e.query,n=await rQ(e,t),{account:r}=await oQ(e,{resolvedUserId:n,selection:e.query}),i=await AY(e.context.socialProviders,{value:r.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Account is not associated with a configured social provider.`,code:`PROVIDER_NOT_CONFIGURED`});let a=await sQ(e,{resolvedUserId:n,selection:e.query,account:r});if(!a.accessToken)throw E.from(`BAD_REQUEST`,{message:`Access token not found`,code:`ACCESS_TOKEN_NOT_FOUND`});let o=await i.getUserInfo({...a,accessToken:a.accessToken});if(!o)throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);return e.json({...o,account:{id:r.id,providerId:r.providerId,accountId:r.accountId}})});async function ppe(e,t,n){if(n.iss&&t.issuer&&n.iss!==t.issuer)return e.context.logger.error(`OAuth issuer mismatch`,{expected:t.issuer,received:n.iss}),{error:Tq.ISSUER_MISMATCH};if(t.requiresIdTokenNonce&&!n.idTokenNonce)return e.context.logger.error(`OAuth id_token nonce binding required but no expected nonce was found in state`,{providerId:t.id}),{error:Tq.NONCE_BINDING_MISSING};let r;try{r=await t.validateAuthorizationCode({code:n.code,codeVerifier:n.codeVerifier,deviceId:n.deviceId,redirectURI:`${e.context.baseURL}${RY(t)}`})}catch(t){return e.context.logger.error(`Failed to validate authorization code`,t),{error:Tq.INVALID_CODE}}if(!r)return{error:Tq.INVALID_CODE};let i=await t.getUserInfo({...r,expectedIdTokenNonce:n.idTokenNonce,user:ye(n.user)??void 0});if(!i?.user)return e.context.logger.error(`Unable to get user info`),{error:Tq.UNABLE_TO_GET_USER_INFO};let a=await NY(t,r,i.data).catch(n=>(e.context.logger.error(`Unable to derive provider account identity`,{providerId:t.id,error:n}),null));return a?{tokens:r,userInfo:i.user,providerProfile:MY(i.data),accountKey:a}:{error:Tq.UNABLE_TO_GET_USER_INFO}}const cQ=A({code:k().optional(),error:k().optional(),device_id:k().optional(),error_description:k().optional(),state:k().optional(),user:k().optional(),iss:k().optional()}),mpe=X(`/callback/:id`,{method:[`GET`,`POST`],operationId:`handleOAuthCallback`,body:cQ.optional(),query:cQ.optional(),metadata:{...Lq,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`]}},async e=>{let t,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if(e.method===`POST`){let t=e.body?cQ.parse(e.body):{},n=e.query?cQ.parse(e.query):{},r=cQ.parse({...t,...n}),i=new URLSearchParams;for(let[e,t]of Object.entries(r))t!=null&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if(e.method===`GET`)t=cQ.parse(e.query);else if(e.method===`POST`)t=cQ.parse(e.body);else throw Error(`Unsupported method`)}catch(t){e.context.logger.error(`INVALID_CALLBACK_REQUEST`,t);let r=Cq(n,new URLSearchParams({error:`invalid_callback_request`}));throw e.redirect(r)}let{code:r,error:i,state:a,error_description:o,device_id:s,user:c,iss:l}=t;if(a===void 0&&r){let t=await AY(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let n=Pq(t),{state:r,codeVerifier:i}=await Fq(e,{idTokenNonce:n}),a=await t.createAuthorizationURL({state:r,codeVerifier:i,idTokenNonce:n,redirectURI:`${e.context.baseURL}${RY(t)}`});throw e.redirect(a.toString())}}if(!a){e.context.logger.error(`State not found`,i);let t=Cq(n,new URLSearchParams({error:`state_not_found`}));throw e.redirect(t)}let{codeVerifier:u,callbackURL:d,link:f,errorURL:p,newUserURL:m,requestSignUp:h,idTokenNonce:g}=await Iq(e);function _(t,r){let i=p??n,a=new URLSearchParams({error:t});r&&a.set(`error_description`,r);let o=Cq(i,a);throw e.redirect(o)}if(i&&_(i,o),!r)throw e.context.logger.warn(`Code not found`),_(Tq.NO_CODE);let v=await AY(e.context.socialProviders,{value:e.params.id});if(!v)throw e.context.logger.warn(`OAuth provider not found`,{providerId:e.params.id}),_(Tq.PROVIDER_NOT_FOUND);let y=await ppe(e,v,{code:r,codeVerifier:u,iss:l,deviceId:s,user:c,idTokenNonce:g});if(y.error)throw _(y.error);let{tokens:b,userInfo:x,providerProfile:S,accountKey:ee}=y,{accountId:C}=ee;if(!d)throw e.context.logger.error(`No callback URL found`),_(Tq.NO_CALLBACK_URL);let te={...ee,...b,scope:b.scopes?.join(`,`)};if(f){let t=await Ofe(e,{link:f,userInfo:x,account:te,profile:S,scopes:b.scopes});if(!t.linked)return _(t.error.code,t.error.message);throw e.redirect(d)}if(!x.email)return e.context.logger.error(Dq(v.id)),_(Tq.EMAIL_NOT_FOUND);let w;try{w=await HZ(e,{userInfo:{...x,id:C,email:x.email,name:x.name||``},account:te,callbackURL:d,disableSignUp:v.disableImplicitSignUp&&!h||v.options?.disableSignUp,overrideUserInfo:v.options?.overrideUserInfoOnSignIn,source:{method:`oauth`,oauth:{providerId:v.id,profile:S}}})}catch(e){throw Rq(e)&&e.body?.code&&_(e.body.code,e.body.message),e}if(w.error)return e.context.logger.error(w.error.split(` `).join(`_`)),_(w.error.split(` `).join(`_`));let{session:ne,user:T}=w.data;await cq(e,{session:ne,user:T});let re;try{re=(w.isRegister&&m||d).toString()}catch{re=w.isRegister&&m||d}throw e.redirect(re)});function lQ(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,`&`)}const hpe=(e,t=`Unknown`,n=null)=>{let r=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
74
|
+
<html lang="en">
|
|
75
|
+
<head>
|
|
76
|
+
<meta charset="UTF-8" />
|
|
77
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
78
|
+
<title>Error</title>
|
|
79
|
+
<style>
|
|
80
|
+
* {
|
|
81
|
+
box-sizing: border-box;
|
|
82
|
+
}
|
|
83
|
+
body {
|
|
84
|
+
font-family: ${r?.font?.defaultFamily||`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`};
|
|
85
|
+
background: ${r?.colors?.background||`var(--background)`};
|
|
86
|
+
color: var(--foreground);
|
|
87
|
+
margin: 0;
|
|
88
|
+
}
|
|
89
|
+
:root,
|
|
90
|
+
:host {
|
|
91
|
+
--spacing: 0.25rem;
|
|
92
|
+
--container-md: 28rem;
|
|
93
|
+
--text-sm: ${r?.size?.textSm||`0.875rem`};
|
|
94
|
+
--text-sm--line-height: calc(1.25 / 0.875);
|
|
95
|
+
--text-2xl: ${r?.size?.text2xl||`1.5rem`};
|
|
96
|
+
--text-2xl--line-height: calc(2 / 1.5);
|
|
97
|
+
--text-4xl: ${r?.size?.text4xl||`2.25rem`};
|
|
98
|
+
--text-4xl--line-height: calc(2.5 / 2.25);
|
|
99
|
+
--text-6xl: ${r?.size?.text6xl||`3rem`};
|
|
100
|
+
--text-6xl--line-height: 1;
|
|
101
|
+
--font-weight-medium: 500;
|
|
102
|
+
--font-weight-semibold: 600;
|
|
103
|
+
--font-weight-bold: 700;
|
|
104
|
+
--default-transition-duration: 150ms;
|
|
105
|
+
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
106
|
+
--radius: ${r?.size?.radiusSm||`0.625rem`};
|
|
107
|
+
--default-mono-font-family: ${r?.font?.monoFamily||`var(--font-geist-mono)`};
|
|
108
|
+
--primary: ${r?.colors?.primary||`black`};
|
|
109
|
+
--primary-foreground: ${r?.colors?.primaryForeground||`white`};
|
|
110
|
+
--background: ${r?.colors?.background||`white`};
|
|
111
|
+
--foreground: ${r?.colors?.foreground||`oklch(0.271 0 0)`};
|
|
112
|
+
--border: ${r?.colors?.border||`oklch(0.89 0 0)`};
|
|
113
|
+
--destructive: ${r?.colors?.destructive||`oklch(0.55 0.15 25.723)`};
|
|
114
|
+
--muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.545 0 0)`};
|
|
115
|
+
--corner-border: ${r?.colors?.cornerBorder||`#404040`};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
button, .btn {
|
|
119
|
+
cursor: pointer;
|
|
120
|
+
background: none;
|
|
121
|
+
border: none;
|
|
122
|
+
color: inherit;
|
|
123
|
+
font: inherit;
|
|
124
|
+
transition: all var(--default-transition-duration)
|
|
125
|
+
var(--default-transition-timing-function);
|
|
126
|
+
}
|
|
127
|
+
button:hover, .btn:hover {
|
|
128
|
+
opacity: 0.8;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
@media (prefers-color-scheme: dark) {
|
|
132
|
+
:root,
|
|
133
|
+
:host {
|
|
134
|
+
--primary: ${r?.colors?.primary||`white`};
|
|
135
|
+
--primary-foreground: ${r?.colors?.primaryForeground||`black`};
|
|
136
|
+
--background: ${r?.colors?.background||`oklch(0.15 0 0)`};
|
|
137
|
+
--foreground: ${r?.colors?.foreground||`oklch(0.98 0 0)`};
|
|
138
|
+
--border: ${r?.colors?.border||`oklch(0.27 0 0)`};
|
|
139
|
+
--destructive: ${r?.colors?.destructive||`oklch(0.65 0.15 25.723)`};
|
|
140
|
+
--muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.65 0 0)`};
|
|
141
|
+
--corner-border: ${r?.colors?.cornerBorder||`#a0a0a0`};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
@media (max-width: 640px) {
|
|
145
|
+
:root, :host {
|
|
146
|
+
--text-6xl: 2.5rem;
|
|
147
|
+
--text-2xl: 1.25rem;
|
|
148
|
+
--text-sm: 0.8125rem;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
@media (max-width: 480px) {
|
|
152
|
+
:root, :host {
|
|
153
|
+
--text-6xl: 2rem;
|
|
154
|
+
--text-2xl: 1.125rem;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
</style>
|
|
158
|
+
</head>
|
|
159
|
+
<body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
|
|
160
|
+
<div
|
|
161
|
+
style="
|
|
162
|
+
display: flex;
|
|
163
|
+
flex-direction: column;
|
|
164
|
+
align-items: center;
|
|
165
|
+
justify-content: center;
|
|
166
|
+
gap: 1.5rem;
|
|
167
|
+
position: relative;
|
|
168
|
+
width: 100%;
|
|
169
|
+
min-height: 100vh;
|
|
170
|
+
padding: 1rem;
|
|
171
|
+
"
|
|
172
|
+
>
|
|
173
|
+
${r?.disableBackgroundGrid?``:`
|
|
174
|
+
<div
|
|
175
|
+
style="
|
|
176
|
+
position: absolute;
|
|
177
|
+
inset: 0;
|
|
178
|
+
background-image: linear-gradient(to right, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px),
|
|
179
|
+
linear-gradient(to bottom, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px);
|
|
180
|
+
background-size: 40px 40px;
|
|
181
|
+
opacity: 0.6;
|
|
182
|
+
pointer-events: none;
|
|
183
|
+
width: 100vw;
|
|
184
|
+
height: 100vh;
|
|
185
|
+
"
|
|
186
|
+
></div>
|
|
187
|
+
<div
|
|
188
|
+
style="
|
|
189
|
+
position: absolute;
|
|
190
|
+
inset: 0;
|
|
191
|
+
display: flex;
|
|
192
|
+
align-items: center;
|
|
193
|
+
justify-content: center;
|
|
194
|
+
background: ${r?.colors?.background||`var(--background)`};
|
|
195
|
+
mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
196
|
+
-webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
197
|
+
pointer-events: none;
|
|
198
|
+
"
|
|
199
|
+
></div>
|
|
200
|
+
`}
|
|
201
|
+
|
|
202
|
+
<div
|
|
203
|
+
style="
|
|
204
|
+
position: relative;
|
|
205
|
+
z-index: 10;
|
|
206
|
+
border: 2px solid var(--border);
|
|
207
|
+
background: ${r?.colors?.cardBackground||`var(--background)`};
|
|
208
|
+
padding: 1.5rem;
|
|
209
|
+
max-width: 42rem;
|
|
210
|
+
width: 100%;
|
|
211
|
+
"
|
|
212
|
+
>
|
|
213
|
+
${r?.disableCornerDecorations?``:`
|
|
214
|
+
<!-- Corner decorations -->
|
|
215
|
+
<div
|
|
216
|
+
style="
|
|
217
|
+
position: absolute;
|
|
218
|
+
top: -2px;
|
|
219
|
+
left: -2px;
|
|
220
|
+
width: 2rem;
|
|
221
|
+
height: 2rem;
|
|
222
|
+
border-top: 4px solid var(--corner-border);
|
|
223
|
+
border-left: 4px solid var(--corner-border);
|
|
224
|
+
"
|
|
225
|
+
></div>
|
|
226
|
+
<div
|
|
227
|
+
style="
|
|
228
|
+
position: absolute;
|
|
229
|
+
top: -2px;
|
|
230
|
+
right: -2px;
|
|
231
|
+
width: 2rem;
|
|
232
|
+
height: 2rem;
|
|
233
|
+
border-top: 4px solid var(--corner-border);
|
|
234
|
+
border-right: 4px solid var(--corner-border);
|
|
235
|
+
"
|
|
236
|
+
></div>
|
|
237
|
+
|
|
238
|
+
<div
|
|
239
|
+
style="
|
|
240
|
+
position: absolute;
|
|
241
|
+
bottom: -2px;
|
|
242
|
+
left: -2px;
|
|
243
|
+
width: 2rem;
|
|
244
|
+
height: 2rem;
|
|
245
|
+
border-bottom: 4px solid var(--corner-border);
|
|
246
|
+
border-left: 4px solid var(--corner-border);
|
|
247
|
+
"
|
|
248
|
+
></div>
|
|
249
|
+
<div
|
|
250
|
+
style="
|
|
251
|
+
position: absolute;
|
|
252
|
+
bottom: -2px;
|
|
253
|
+
right: -2px;
|
|
254
|
+
width: 2rem;
|
|
255
|
+
height: 2rem;
|
|
256
|
+
border-bottom: 4px solid var(--corner-border);
|
|
257
|
+
border-right: 4px solid var(--corner-border);
|
|
258
|
+
"
|
|
259
|
+
></div>`}
|
|
260
|
+
|
|
261
|
+
<div style="text-align: center; margin-bottom: 1.5rem;">
|
|
262
|
+
<div style="margin-bottom: 1.5rem;">
|
|
263
|
+
<div
|
|
264
|
+
style="
|
|
265
|
+
display: inline-block;
|
|
266
|
+
border: 2px solid ${r?.disableTitleBorder?`transparent`:r?.colors?.titleBorder||`var(--destructive)`};
|
|
267
|
+
padding: 0.375rem 1rem;
|
|
268
|
+
"
|
|
269
|
+
>
|
|
270
|
+
<h1
|
|
271
|
+
style="
|
|
272
|
+
font-size: var(--text-6xl);
|
|
273
|
+
font-weight: var(--font-weight-semibold);
|
|
274
|
+
color: ${r?.colors?.titleColor||`var(--foreground)`};
|
|
275
|
+
letter-spacing: -0.02em;
|
|
276
|
+
margin: 0;
|
|
277
|
+
"
|
|
278
|
+
>
|
|
279
|
+
ERROR
|
|
280
|
+
</h1>
|
|
281
|
+
</div>
|
|
282
|
+
<div
|
|
283
|
+
style="
|
|
284
|
+
height: 2px;
|
|
285
|
+
background-color: var(--border);
|
|
286
|
+
width: calc(100% + 3rem);
|
|
287
|
+
margin-left: -1.5rem;
|
|
288
|
+
margin-top: 1.5rem;
|
|
289
|
+
"
|
|
290
|
+
></div>
|
|
291
|
+
</div>
|
|
292
|
+
|
|
293
|
+
<h2
|
|
294
|
+
style="
|
|
295
|
+
font-size: var(--text-2xl);
|
|
296
|
+
font-weight: var(--font-weight-semibold);
|
|
297
|
+
color: var(--foreground);
|
|
298
|
+
margin: 0 0 1rem;
|
|
299
|
+
"
|
|
300
|
+
>
|
|
301
|
+
Something went wrong
|
|
302
|
+
</h2>
|
|
303
|
+
|
|
304
|
+
<div
|
|
305
|
+
style="
|
|
306
|
+
display: inline-flex;
|
|
307
|
+
align-items: center;
|
|
308
|
+
gap: 0.5rem;
|
|
309
|
+
border: 2px solid var(--border);
|
|
310
|
+
background-color: var(--muted);
|
|
311
|
+
padding: 0.375rem 0.75rem;
|
|
312
|
+
margin: 0 0 1rem;
|
|
313
|
+
flex-wrap: wrap;
|
|
314
|
+
justify-content: center;
|
|
315
|
+
"
|
|
316
|
+
>
|
|
317
|
+
<span
|
|
318
|
+
style="
|
|
319
|
+
font-size: 0.75rem;
|
|
320
|
+
color: var(--muted-foreground);
|
|
321
|
+
font-weight: var(--font-weight-semibold);
|
|
322
|
+
"
|
|
323
|
+
>
|
|
324
|
+
CODE:
|
|
325
|
+
</span>
|
|
326
|
+
<span
|
|
327
|
+
style="
|
|
328
|
+
font-size: var(--text-sm);
|
|
329
|
+
font-family: var(--default-mono-font-family, monospace);
|
|
330
|
+
color: var(--foreground);
|
|
331
|
+
word-break: break-all;
|
|
332
|
+
"
|
|
333
|
+
>
|
|
334
|
+
${lQ(t)}
|
|
335
|
+
</span>
|
|
336
|
+
</div>
|
|
337
|
+
|
|
338
|
+
<p
|
|
339
|
+
style="
|
|
340
|
+
color: var(--muted-foreground);
|
|
341
|
+
max-width: 28rem;
|
|
342
|
+
margin: 0 auto;
|
|
343
|
+
font-size: var(--text-sm);
|
|
344
|
+
line-height: 1.5;
|
|
345
|
+
text-wrap: pretty;
|
|
346
|
+
"
|
|
347
|
+
>
|
|
348
|
+
${n||`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`}
|
|
349
|
+
</p>
|
|
350
|
+
</div>
|
|
351
|
+
|
|
352
|
+
<div
|
|
353
|
+
style="
|
|
354
|
+
display: flex;
|
|
355
|
+
gap: 0.75rem;
|
|
356
|
+
margin-top: 1.5rem;
|
|
357
|
+
justify-content: center;
|
|
358
|
+
flex-wrap: wrap;
|
|
359
|
+
"
|
|
360
|
+
>
|
|
361
|
+
<a
|
|
362
|
+
href="/"
|
|
363
|
+
style="
|
|
364
|
+
text-decoration: none;
|
|
365
|
+
"
|
|
366
|
+
>
|
|
367
|
+
<div
|
|
368
|
+
style="
|
|
369
|
+
border: 2px solid var(--border);
|
|
370
|
+
background: var(--primary);
|
|
371
|
+
color: var(--primary-foreground);
|
|
372
|
+
padding: 0.5rem 1rem;
|
|
373
|
+
border-radius: 0;
|
|
374
|
+
white-space: nowrap;
|
|
375
|
+
"
|
|
376
|
+
class="btn"
|
|
377
|
+
>
|
|
378
|
+
Go Home
|
|
379
|
+
</div>
|
|
380
|
+
</a>
|
|
381
|
+
<a
|
|
382
|
+
href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
|
|
383
|
+
target="_blank"
|
|
384
|
+
rel="noopener noreferrer"
|
|
385
|
+
style="
|
|
386
|
+
text-decoration: none;
|
|
387
|
+
"
|
|
388
|
+
>
|
|
389
|
+
<div
|
|
390
|
+
style="
|
|
391
|
+
border: 2px solid var(--border);
|
|
392
|
+
background: transparent;
|
|
393
|
+
color: var(--foreground);
|
|
394
|
+
padding: 0.5rem 1rem;
|
|
395
|
+
border-radius: 0;
|
|
396
|
+
white-space: nowrap;
|
|
397
|
+
"
|
|
398
|
+
class="btn"
|
|
399
|
+
>
|
|
400
|
+
Ask AI
|
|
401
|
+
</div>
|
|
402
|
+
</a>
|
|
403
|
+
</div>
|
|
404
|
+
</div>
|
|
405
|
+
</div>
|
|
406
|
+
</body>
|
|
407
|
+
</html>`},gpe=X(`/error`,{method:`GET`,metadata:{...Lq,openapi:{description:`Displays an error page`,responses:{200:{description:`Success`,content:{"text/html":{schema:{type:`string`,description:`The HTML content of the error page`}}}}}}}},async e=>{let t=new URL(e.request?.url||``),n=t.searchParams.get(`error`)||`UNKNOWN`,r=t.searchParams.get(`error_description`)||null,i=/^[\'A-Za-z0-9_-]+$/.test(n||``)?n:`UNKNOWN`,a=r?lQ(r):null,o=new URLSearchParams;o.set(`error`,i),r&&o.set(`error_description`,r);let s=e.context.options,c=s.onAPIError?.errorURL;if(c){let e=Cq(c,o);return new Response(null,{status:302,headers:{Location:e}})}return ae&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(hpe(e.context.options,i,a),{headers:{"Content-Type":`text/html`}})}),_pe=X(`/ok`,{method:`GET`,metadata:{...Lq,openapi:{description:`Check if the API is working`,responses:{200:{description:`API is working`,content:{"application/json":{schema:{type:`object`,properties:{ok:{type:`boolean`,description:`Indicates if the API is working`}},required:[`ok`]}}}}}}}},async e=>e.json({ok:!0}));function uQ(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn(`Password is too short`),E.from(`BAD_REQUEST`,Y.PASSWORD_TOO_SHORT)}function dQ(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn(`Password is too long`),E.from(`BAD_REQUEST`,Y.PASSWORD_TOO_LONG)}async function vpe(e,t,n,r){await DH(e.context.adapter,async()=>{await r?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t)?await e.context.internalAdapter.updatePassword(t,n):await e.context.internalAdapter.createAccount({userId:t,providerId:`credential`,accountId:t,password:n})})}async function ype(e,t){dQ(e,t.password);let n=await e.context.internalAdapter.findCredentialAccount(t.userId),r=n?.password;return!n||!r?!1:await e.context.password.verify({hash:r,password:t.password})}async function bpe(e,t){let n=t.body.password;typeof n==`string`&&dQ(t,n);let r=await t.context.internalAdapter.findCredentialAccount(e),i=r?.password;if(!r||!i||!n)throw n&&await t.context.password.hash(n),E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);if(!await t.context.password.verify({hash:i,password:n}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return!0}function fQ(e,t,n){let r=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}function xpe(e,t,n){let r=new URL(t,e.baseURL);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}const Spe=X(`/request-password-reset`,{method:`POST`,body:A({email:Ve().meta({description:`The email address of the user to send a password reset email to`}),redirectTo:k().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:`requestPasswordReset`,description:`Send a password reset email to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`},message:{type:`string`}}}}}}}}},use:[iJ(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error(`Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!`),E.from(`BAD_REQUEST`,{message:`Reset password isn't enabled`,code:`RESET_PASSWORD_DISABLED`});let{email:t,redirectTo:n}=e.body,r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)return ge(24),await e.context.internalAdapter.findVerificationValue(`dummy-verification-token`),e.context.logger.warn(`Reset Password: User not found`),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`});let i=pG(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,`sec`),a=ge(24);await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=n?encodeURIComponent(n):``,s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:r.user,url:s,token:a},e.request)),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`})}),Cpe=X(`/reset-password/:token`,{method:`GET`,operationId:`resetPasswordCallback`,query:A({callbackURL:k().meta({description:`The URL to redirect the user to reset their password`})}),use:[iJ(e=>e.query.callbackURL)],metadata:{openapi:{operationId:`resetPasswordCallback`,description:`Redirects the user to the callback URL with the token`,parameters:[{name:`token`,in:`path`,required:!0,description:`The token to reset the password`,schema:{type:`string`}},{name:`callbackURL`,in:`query`,required:!0,description:`The URL to redirect the user to reset their password`,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:n}=e.query;if(!t||!n)throw e.redirect(fQ(e.context,n,{error:`INVALID_TOKEN`}));let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt</* @__PURE__ */ new Date?e.redirect(fQ(e.context,n,{error:`INVALID_TOKEN`})):e.redirect(xpe(e.context,n,{token:t}))}),wpe=X(`/reset-password`,{method:`POST`,operationId:`resetPassword`,query:A({token:k().optional()}).optional(),body:A({newPassword:k().meta({description:`The new password to set`}),token:k().meta({description:`The token to reset the password`}).optional()}),metadata:{openapi:{operationId:`resetPassword`,description:`Reset the password for a user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN);let{newPassword:n}=e.body;uQ(e,n),dQ(e,n);let r=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(r);if(!i||i.expiresAt</* @__PURE__ */ new Date)throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN);let a=i.value,o=await e.context.internalAdapter.findUserById(a);if(!o)throw E.from(`BAD_REQUEST`,Y.USER_NOT_FOUND);return await vpe(e,a,await e.context.password.hash(n),async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(r))throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:o},e.request),e.json({status:!0})}),Tpe=X(`/verify-password`,{method:`POST`,body:A({password:k().meta({description:`The password to verify`})}),metadata:{scope:`server`,openapi:{operationId:`verifyPassword`,description:`Verify the current user's password`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}},use:[GJ]},async e=>{let{password:t}=e.body,n=e.context.session;if(!await ype(e,{password:t,userId:n.user.id}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return e.json({status:!0})}),Epe=A({callbackURL:k().meta({description:`Callback URL to redirect to after the user has signed in`}).optional(),newUserCallbackURL:k().optional(),errorCallbackURL:k().meta({description:`Callback URL to redirect to if an error happens`}).optional(),provider:tQ,disableRedirect:Je().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),idToken:at(A({token:k().meta({description:`ID token from the provider`}),nonce:k().meta({description:`Nonce used to generate the token`}).optional(),accessToken:k().meta({description:`Access token from the provider`}).optional(),refreshToken:k().meta({description:`Refresh token from the provider`}).optional(),expiresAt:Le().meta({description:`Expiry date of the token`}).optional(),user:A({name:A({firstName:k().optional(),lastName:k().optional()}).optional(),email:k().optional()}).meta({description:`The user object from the provider. Only available for some providers like Apple.`}).optional()})),scopes:Be(k()).meta({description:`Array of scopes to request from the provider. This will override the default scopes passed.`}).optional(),requestSignUp:Je().meta({description:`Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider`}).optional(),loginHint:k().meta({description:`The login hint to use for the authorization code request`}).optional(),additionalParams:QY,additionalData:ze(k(),et()).optional().meta({description:`Additional data to be passed through the OAuth flow`})}),Dpe=()=>X(`/sign-in/social`,{method:`POST`,operationId:`socialSignIn`,body:Epe,metadata:{$Infer:{body:{},returned:{}},openapi:{description:`Sign in with a social provider`,operationId:`socialSignIn`,responses:{200:{description:`Success - Returns session details (idToken branch) or an authorize URL (redirect branch)`,content:{"application/json":{schema:{type:`object`,description:`Returns session details when idToken is provided, or an authorize URL otherwise`,properties:{token:{type:`string`},user:{type:`object`,$ref:`#/components/schemas/User`},url:{type:`string`},redirect:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=await AY(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!zZ(t))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:r}=e.body.idToken;if(!await BZ(t,n,r,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.INVALID_TOKEN);let i={idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},a=await t.getUserInfo(i);if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(Dq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await PY(t,i,a.data),s=MY(a.data),c=await HZ(e,{userInfo:{...a.user,email:a.user.email,id:o.accountId,name:a.user.name||``,image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{...o,accessToken:e.body.idToken.accessToken,idToken:n},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:`oauth`,oauth:{providerId:t.id,profile:s}}});if(c.error)throw c.error===Tq.EMAIL_NOT_VERIFIED?E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED):E.from(`UNAUTHORIZED`,{message:c.error,code:`OAUTH_LINK_ERROR`});return await cq(e,c.data),e.json({redirect:!1,token:c.data.session.token,url:void 0,user:rG(e.context.options,c.data.user)})}let n=Pq(t),{codeVerifier:r,state:i}=await Fq(e,{additionalData:e.body.additionalData,idTokenNonce:n}),a=await t.createAuthorizationURL({state:i,codeVerifier:r,idTokenNonce:n,redirectURI:`${e.context.baseURL}${RY(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),Ope=()=>X(`/sign-in/email`,{method:`POST`,operationId:`signInEmail`,use:[oJ],cloneRequest:!0,body:A({email:k().meta({description:`Email of the user`}),password:k().meta({description:`Password of the user`}),callbackURL:k().meta({description:`Callback URL to use as a redirect for email verification`}).optional(),rememberMe:Je().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signInEmail`,description:`Sign in with email and password`,responses:{200:{description:`Success - Returns either session details or redirect URL`,content:{"application/json":{schema:{type:`object`,description:`Session response when idToken is provided`,properties:{redirect:{type:`boolean`,enum:[!1]},token:{type:`string`,description:`Session token`},url:{type:`string`,nullable:!0},user:{type:`object`,$ref:`#/components/schemas/User`}},required:[`redirect`,`token`,`user`]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),E.from(`BAD_REQUEST`,{code:`EMAIL_PASSWORD_DISABLED`,message:`Email and password is not enabled`});let{email:t,password:n}=e.body;if(!Ve().safeParse(t).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);dQ(e,n);let r=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),i=r?.accounts.find(e=>e.providerId===`credential`&&e.accountId===r.user.id);if(!r||!i)throw await e.context.password.hash(n),e.context.logger.warn(`User not found`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);let a=r.user,o=i.password;if(!o)throw await e.context.password.hash(n),e.context.logger.warn(`Password not found`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:o,password:n}))throw e.context.logger.warn(`Invalid password`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!a.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await BY(e.context.secret,a.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:a,url:r,token:t},zY(e.request)))}throw E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(a.id,e.body.rememberMe===!1);if(!s)throw e.context.logger.error(`Failed to create session`),E.from(`UNAUTHORIZED`,Y.FAILED_TO_CREATE_SESSION);return await cq(e,{session:s,user:a},e.body.rememberMe===!1),e.body.callbackURL&&e.setHeader(`Location`,e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:rG(e.context.options,a)})}),kpe=A({callbackURL:k().meta({description:`The URL to redirect to after provider logout`}).optional(),disableRedirect:Je().meta({description:`Return the provider logout URL without redirecting`}).optional(),state:k().meta({description:`State to pass to the provider logout endpoint`}).optional()}).optional(),pQ=e=>({success:!0,url:e?.url,redirect:e?.redirect}),Ape=X(`/sign-out`,{method:`POST`,body:kpe,operationId:`signOut`,requireHeaders:!0,metadata:{openapi:{operationId:`signOut`,description:`Sign out the current user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`},url:{type:`string`,description:`Provider logout URL when RP-initiated logout is available`},redirect:{type:`boolean`,description:`Whether the client should redirect to the provider logout URL`}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),n=null;if(t)try{n=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error(`Failed to read session from database`,t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error(`Failed to delete session from database`,t)}fq(e);let r=await(async()=>{try{if(!n)return null;let t=await e.context.internalAdapter.findAccounts(n.user.id),r=new Map(e.context.socialProviders.map(e=>[e.id,e])),i=t.filter(e=>!!r.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(i.length===0)return null;let a=/* @__PURE__ */ new Set,o=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of i){if(a.has(t.providerId))continue;a.add(t.providerId);let n=r.get(t.providerId);try{let r=await n?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:o,state:e.body?.state});if(r)return r.toString()}catch(n){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,n)}}return null}catch(t){return e.context.logger.error(`Failed to create provider logout URL`,t),null}})();if(r){let t=!e.body?.disableRedirect;return t&&e.setHeader(`Location`,r),e.json(pQ({url:r,redirect:t}))}return e.json(pQ())}),jpe=A({name:k(),email:Ve(),password:k().nonempty(),image:k().optional(),callbackURL:k().optional(),rememberMe:Je().optional()}).and(ze(k(),et())),Mpe=()=>X(`/sign-up/email`,{method:`POST`,operationId:`signUpWithEmailAndPassword`,use:[oJ],body:jpe,cloneRequest:!0,metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signUpWithEmailAndPassword`,description:`Sign up a user using email and password`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},email:{type:`string`,description:`The email of the user`},password:{type:`string`,description:`The password of the user`},image:{type:`string`,description:`The profile image URL of the user`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`},rememberMe:{type:`boolean`,description:"If this is false, the session will not be remembered. Default is `true`."}},required:[`name`,`email`,`password`]}}}},responses:{200:{description:`Successfully created user`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`Authentication token for the session`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}},422:{description:`Unprocessable Entity. User already exists or failed to create user.`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}}}}}}},async e=>DH(e.context.adapter,async()=>{if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw E.from(`BAD_REQUEST`,{message:`Email and password sign up is not enabled`,code:`EMAIL_PASSWORD_SIGN_UP_DISABLED`});let t=e.body,{name:n,email:r,password:i,image:a,callbackURL:o,rememberMe:s,...c}=t;if(!Ve().safeParse(r).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);if(!i||typeof i!=`string`)throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);uQ(e,i),dQ(e,i);let l=e.context.options.emailAndPassword.requireEmailVerification||e.context.options.emailAndPassword.autoSignIn===!1,u=e.context.options.emailAndPassword.autoSignIn===!1||l,d=cG(e.context.options,c,`create`),f=r.toLowerCase(),m=()=>{let t=/* @__PURE__ */ new Date,r=e.context.generateId({model:`user`})||ge(),i={name:n,email:f,emailVerified:!1,image:a??null,createdAt:t,updatedAt:t},o=e.context.options.emailAndPassword?.customSyntheticUser,s;if(o){let t=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of t)e in d&&(n[e]=d[e]);let a=o({coreFields:i,additionalFields:n,id:r});s=iG(e.context.options,a)}else s=iG(e.context.options,{...i,...d,id:r});return e.json({token:null,user:rG(e.context.options,s)})},h=await e.context.internalAdapter.findUserByEmail(f);if(h?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${r}`),l)return await e.context.password.hash(i),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:h.user},zY(e.request))),m();throw E.from(`UNPROCESSABLE_ENTITY`,Y.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let g=await e.context.password.hash(i),_;try{if(_=await e.context.internalAdapter.createUser({email:f,name:n,image:a,...d,emailVerified:!1},{method:`email-password`}),!_)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_USER)}catch(t){if(Rq(t)){if(t.statusCode===403&&l)return m();throw t}throw p()&&e.context.logger.error(`Failed to create user`,t),e.context.logger?.error(`Failed to create user`,t),E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER)}if(!_)throw E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:_.id,providerId:`credential`,accountId:_.id,password:g}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await BY(e.context.secret,_.email,void 0,e.context.options.emailVerification?.expiresIn),r=t.callbackURL?encodeURIComponent(t.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:_,url:i,token:n},zY(e.request)))}if(u)return e.json({token:null,user:rG(e.context.options,_)});let v=await e.context.internalAdapter.createSession(_.id,s===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!v)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_SESSION);return await cq(e,{session:v,user:_},s===!1),e.json({token:v.token,user:rG(e.context.options,_)})})),Npe=ze(k().meta({description:`Field name must be a string`}),et()),Ppe=()=>X(`/update-session`,{method:`POST`,operationId:`updateSession`,body:Npe,use:[WJ],metadata:{$Infer:{body:{}},openapi:{operationId:`updateSession`,description:`Update the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{session:{type:`object`,$ref:`#/components/schemas/Session`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,Y.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,r=uG(e.context.options,t,`update`);if(Object.keys(r).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let i=await e.context.internalAdapter.updateSession(n.session.token,{...r,updatedAt:/* @__PURE__ */ new Date});if(!i&&VJ(e))throw fq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let a=i??{...n.session,...r,updatedAt:/* @__PURE__ */ new Date};return await cq(e,{session:a,user:n.user}),e.json({session:aG(e.context.options,a)})}),Fpe=ze(k().meta({description:`Field name must be a string`}),et()),Ipe=()=>X(`/update-user`,{method:`POST`,operationId:`updateUser`,body:Fpe,use:[WJ],metadata:{$Infer:{body:{}},openapi:{operationId:`updateUser`,description:`Update the current user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},image:{type:`string`,description:`The image of the user`,nullable:!0}}}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,Y.BODY_MUST_BE_AN_OBJECT);if(t.email)throw E.from(`BAD_REQUEST`,Y.EMAIL_CAN_NOT_BE_UPDATED);let{name:n,image:r,...i}=t,a=e.context.session,o=cG(e.context.options,i,`update`);if(r===void 0&&n===void 0&&Object.keys(o).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:n,image:r,...o})??{...a.user,...n!==void 0&&{name:n},...r!==void 0&&{image:r},...o};return await cq(e,{session:a.session,user:s}),e.json({status:!0})}),Lpe=X(`/change-password`,{method:`POST`,operationId:`changePassword`,body:A({newPassword:k().meta({description:`The new password to set`}),currentPassword:k().meta({description:`The current password is required`}),revokeOtherSessions:Je().meta({description:`Must be a boolean value`}).optional()}),use:[GJ],metadata:{openapi:{operationId:`changePassword`,description:`Change the password of the user`,responses:{200:{description:`Password successfully changed`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`New session token if other sessions were revoked`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}}}}}},async e=>{let{newPassword:t,currentPassword:n,revokeOtherSessions:r}=e.body,i=e.context.session;uQ(e,t),dQ(e,t),dQ(e,n);let a=await e.context.internalAdapter.findCredentialAccount(i.user.id);if(!a||!a.password)throw E.from(`BAD_REQUEST`,Y.CREDENTIAL_ACCOUNT_NOT_FOUND);let o=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:n}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);let s=await DH(e.context.adapter,async()=>{if(r&&await e.context.internalAdapter.deleteUserSessions(i.user.id),await e.context.internalAdapter.updateAccount(a.id,{password:o}),!r)return null;let t=await e.context.internalAdapter.createSession(i.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION);return t}),c=null;return s&&(await cq(e,{session:s,user:i.user}),c=s.token),e.json({token:c,user:rG(e.context.options,i.user)})}),Rpe=X.serverOnly({method:`POST`,body:A({newPassword:k().meta({description:`The new password to set is required`})}),use:[GJ]},async e=>{let{newPassword:t}=e.body,n=e.context.session;uQ(e,t),dQ(e,t);let r=await e.context.internalAdapter.findCredentialAccount(n.user.id),i=await e.context.password.hash(t);if(!r)return await e.context.internalAdapter.linkAccount({userId:n.user.id,providerId:`credential`,accountId:n.user.id,password:i}),e.json({status:!0});if(!r.password)return await e.context.internalAdapter.updateAccount(r.id,{password:i}),e.json({status:!0});throw E.from(`BAD_REQUEST`,Y.PASSWORD_ALREADY_SET)}),zpe=X(`/delete-user`,{method:`POST`,use:[GJ],body:A({callbackURL:k().meta({description:`The callback URL to redirect to after the user is deleted`}).optional(),password:k().meta({description:`The password of the user is required to delete the user`}).optional(),token:k().meta({description:`The token to delete the user is required`}).optional()}),metadata:{openapi:{operationId:`deleteUser`,description:`Delete the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{callbackURL:{type:`string`,description:`The callback URL to redirect to after the user is deleted`},password:{type:`string`,description:`The user's password. Required if session is not fresh`},token:{type:`string`,description:`The deletion verification token`}}}}}},responses:{200:{description:`User deletion processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the operation was successful`},message:{type:`string`,enum:[`User deleted`,`Verification email sent`],description:`Status message of the deletion process`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.fromStatus(`NOT_FOUND`);let t=e.context.session;if(e.body.password){dQ(e,e.body.password);let n=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!n||!n.password)throw E.from(`BAD_REQUEST`,Y.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD)}if(e.body.token)return await mQ({...e,query:{token:e.body.token}}),e.json({success:!0,message:`User deleted`});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=ZH(32,`0-9`,`a-z`);await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1e3)});let r=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:r,token:n},e.request)),e.json({success:!0,message:`Verification email sent`})}if(!e.body.password&&e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`BAD_REQUEST`,Y.SESSION_EXPIRED)}let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),fq(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(t.user,e.request),e.json({success:!0,message:`User deleted`})}),mQ=X(`/delete-user/callback`,{method:`GET`,query:A({token:k().meta({description:`The token to verify the deletion request`}),callbackURL:k().meta({description:`The URL to redirect to after deletion`}).optional()}),use:[iJ(e=>e.query.callbackURL)],metadata:{openapi:{description:`Callback to complete user deletion with verification token`,responses:{200:{description:`User successfully deleted`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the deletion was successful`},message:{type:`string`,enum:[`User deleted`],description:`Confirmation message`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.from(`NOT_FOUND`,{message:`Not found`,code:`NOT_FOUND`});let t=await HJ(e,{disableCookieCache:VJ(e)});if(!t)throw E.from(`NOT_FOUND`,Y.FAILED_TO_GET_USER_INFO);let n=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!n||n.value!==t.user.id)throw E.from(`NOT_FOUND`,Y.INVALID_TOKEN);let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),fq(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||`/`);return e.json({success:!0,message:`User deleted`})}),Bpe=X(`/change-email`,{method:`POST`,body:A({newEmail:Ve().meta({description:`The new email address to set must be a valid email address`}),callbackURL:k().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[GJ],metadata:{openapi:{operationId:`changeEmail`,responses:{200:{description:`Email change request processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the request was successful`},message:{type:`string`,enum:[`Email updated`,`Verification email sent`],description:`Status message of the email change process`,nullable:!0}},required:[`status`]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error(`Change email is disabled.`),E.from(`BAD_REQUEST`,Y.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn(`Email is the same`),E.fromStatus(`BAD_REQUEST`,{message:`Email is the same`});let n=e.context.session.user.emailVerified!==!0&&e.context.options.user.changeEmail.updateEmailWithoutVerification,r=e.context.options.emailVerification?.sendVerificationEmail,i=r&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!n&&!i&&!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});if(await e.context.internalAdapter.findUserByEmail(t))return await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info(`Change email attempt for existing email`),e.json({status:!0});if(n){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await cq(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),r){let n=await BY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:i,token:n},e.request))}return e.json({status:!0})}if(i){let n=await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-confirmation`}),r=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:r,token:n},e.request)),e.json({status:!0})}if(!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});let a=await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),hQ=sY((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),gQ=/* @__PURE__ */ new WeakMap;function _Q(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function vQ(e,t){t&&t.forEach((t,n)=>{e.responseHeaders?n.toLowerCase()===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t):e.responseHeaders=new Headers({[n]:t})})}function yQ(e){let t=e[Fe],n=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!n)return null;let r=new Headers;return t?.forEach((e,t)=>{r.append(t,e)}),n?.forEach((e,t)=>{t.toLowerCase()===`set-cookie`?r.append(t,e):r.set(t,e)}),r}async function Vpe(e,t,n,r){let i=ue(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=gQ.get(o.handler)??`unknown`;throw e.context.logger.error(`An error occurred during ${n} hook matcher execution:`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`An error occurred during hook matcher execution. Check the logs for more details.`})}if(!t)continue;let s=gQ.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[ve]:`before`,[fe]:c,[be]:s,[pe]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw Rq(t)&&w(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});vQ(e.context,l?.headers);let u=l?.response;if(u&&typeof u==`object`){if(`context`in u&&typeof u.context==`object`){let{headers:e,...t}=u.context;e instanceof Headers&&(a.headers?e.forEach((e,t)=>{a.headers?.set(t,e)}):a.headers=e),a=hQ(t,a);continue}return u}}return{context:a}}async function Hpe(e,t,n,r){let i=ue(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=gQ.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[ve]:`after`,[fe]:o,[be]:t,[pe]:r},()=>a.handler(e)).catch(t=>{if(Rq(t))return w(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:yQ(t)};throw t});vQ(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function Upe(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(gQ.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(gQ.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(gQ.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(gQ.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function bQ(e,t){let n=ue(t.context.options),r=t.operationId??_Q(e),i=e.path??`/:virtual`,a=e.options?.method,o=Array.isArray(a)?a[0]:a,s=t.method??t.request?.method??o??`?`,c=t.asResponse??GH(t.request),l={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return n(`${s} ${i}`,{[fe]:i,[pe]:r},async()=>_H(l,async()=>{let{beforeHooks:a,afterHooks:o}=Upe(l.context),s=await Vpe(l,a,e,r);if(`context`in s&&s.context&&typeof s.context==`object`){let{headers:e,...t}=s.context;if(e){l.headers||(l.headers=new Headers);let t=l.headers;e.forEach((e,n)=>{t.set(n,e)})}l=hQ(t,l)}else if(s){let e=l.context.responseHeaders;return c?aK(s,{headers:e}):t.returnHeaders?{headers:e,response:s}:s}l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let u=await _H(l,()=>n(`handler ${i}`,{[fe]:i,[pe]:r},()=>e(l))).catch(e=>{if(Rq(e))return{response:e,status:e.statusCode,headers:yQ(e)};throw e});if(u instanceof Response)return u;l.context.returned=u.response,l.context.responseHeaders=u.headers??void 0;let d=await Hpe(l,o,e,r);if(d.response!==void 0&&(u.response=d.response),u.headers=d.headers??u.headers,Rq(u.response)&&w(l.context.logger.level,`debug`)&&(u.response.stack=u.response.errorStack),Rq(u.response)&&!c)throw u.headers&&Object.defineProperty(u.response,Fe,{enumerable:!1,configurable:!0,writable:!1,value:u.headers}),u.response;return c?aK(u.response,{headers:u.headers??void 0,status:u.status}):t.returnHeaders?t.returnStatus?{headers:u.headers,response:u.response,status:u.status}:{headers:u.headers,response:u.response}:t.returnStatus?{response:u.response,status:u.status}:u.response}))}async function Wpe(e,t){if(e.baseURL)return e;let n=DY(t),r=e.options.baseURL,i=WH(r)&&!!r.fallback;if(n===void 0&&!i)throw new E(`INTERNAL_SERVER_ERROR`,{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await kY(e,n,OY(e.options))}catch(e){throw e instanceof D?new E(`INTERNAL_SERVER_ERROR`,{message:e.message}):e}}function Gpe(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=async e=>{let n=_Q(i,r),a=async()=>{let r=await t,a=r.checkSchema?.();a&&await a;let o=WH(r.options.baseURL)?await Wpe(r,e):r;return bQ(i,{...e,context:o,operationId:n,asResponse:e?.asResponse??GH(e?.request)})};return await yH()?a():xH(/* @__PURE__ */ new WeakMap,a)},n[r].path=i.path,n[r].options=i.options;return n}function Kpe(e,t){let n=/* @__PURE__ */ new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,r]of Object.entries(e.endpoints))if(r&&`path`in r&&typeof r.path==`string`){let i=r.path,a=[];r.options&&`method`in r.options&&(Array.isArray(r.options.method)?a=r.options.method:typeof r.options.method==`string`&&(a=[r.options.method])),a.length===0&&(a=[`*`]),n.has(i)||n.set(i,[]),n.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let r=[];for(let[e,t]of n.entries())if(t.length>1){let n=/* @__PURE__ */ new Map,i=!1;for(let e of t)for(let r of e.methods)n.has(r)||n.set(r,[]),n.get(r).push(e.pluginId),n.get(r).length>1&&(i=!0),(r===`*`&&t.length>1||r!==`*`&&n.has(`*`))&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,r]of n.entries())(r.length>1||e===`*`&&t.length>1||e!==`*`&&n.has(`*`))&&a.push(e);r.push({path:e,plugins:i,conflictingMethods:a})}}if(r.length>0){let e=r.map(e=>` - "${e.path}" [${e.conflictingMethods.join(`, `)}] used by plugins: ${e.plugins.join(`, `)}`).join(`
|
|
408
|
+
`);t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
409
|
+
${e}
|
|
410
|
+
|
|
411
|
+
To resolve this, you can:
|
|
412
|
+
1. Use only one of the conflicting plugins
|
|
413
|
+
2. Configure the plugins to use different paths (if supported)
|
|
414
|
+
3. Ensure plugins use different HTTP methods for the same path
|
|
415
|
+
`)}}function xQ(e,t){let n=ue(t),r=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},i=t.plugins?.map(t=>t.middlewares?.map(r=>{let i=(async i=>{let a=await e;return n(`middleware ${r.path} ${t.id}`,{"better_auth.hook.type":`middleware`,"http.route":r.path,"better_auth.context":`plugin:${t.id}`},()=>r.middleware({...i,context:{...a,...i.context}}))});return i.options=r.middleware.options,{path:r.path,middleware:i}})).filter(e=>e!==void 0).flat()||[];return{api:Gpe({signInSocial:Dpe(),callbackOAuth:mpe,getSession:BJ(),signOut:Ape,signUpEmail:Mpe(),signInEmail:Ope(),resetPassword:wpe,verifyPassword:Tpe,verifyEmail:UY,sendVerificationEmail:HY,changeEmail:Bpe,changePassword:Lpe,setPassword:Rpe,updateSession:Ppe(),updateUser:Ipe(),deleteUser:zpe,requestPasswordReset:Spe,requestPasswordResetCallback:Cpe,listSessions:qJ(),revokeSession:JJ,revokeSessions:YJ,revokeOtherSessions:XJ,linkSocialAccount:cpe,listUserAccounts:spe,deleteUserCallback:mQ,unlinkAccount:lpe,refreshToken:dpe,getAccessToken:upe,accountInfo:fpe,...r,ok:_pe,error:gpe},e),middlewares:i}}const qpe=(e,t)=>{let n=ue(t),{api:r,middlewares:i}=xQ(e,t),a=new URL(e.baseURL).pathname;return BK(r,{routerContext:e,openapi:{disabled:!0},basePath:a,routerMiddleware:[{path:`/**`,middleware:rJ},...i],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],i=xq(t.url,a);if(r.includes(i))return new Response(`Not Found`,{status:404});let o=e.checkSchema?.();o&&await o;let s=t,c=await LJ(s,e);if(c)return c;for(let t of e.options.plugins||[])if(t.onRequest){let r=await n(`onRequest ${t.id}`,{[ve]:`onRequest`,[be]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(r&&`response`in r)return r.response;r&&`request`in r&&(s=r.request)}return s},async onResponse(t,r){for(let r of e.options.plugins||[])if(r.onResponse){let i=await n(`onResponse ${r.id}`,{[ve]:`onResponse`,[be]:`plugin:${r.id}`,[eee]:t.status},()=>r.onResponse(t,e));if(i)return i.response}return t},async onError(n){if(Rq(n)&&n.status===`FOUND`)return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){try{await t.onAPIError.onError(n,e)}catch(t){e.logger.error(`onAPIError.onError threw`,t)}return}let r=t.logger?.level,i=r===`error`||r===`warn`||r===`debug`?C:void 0;if(t.logger?.disabled!==!0){if(n&&typeof n==`object`&&`message`in n&&typeof n.message==`string`&&(n.message.includes(`no column`)||n.message.includes(`column`)||n.message.includes(`relation`)||n.message.includes(`table`)||n.message.includes(`does not exist`))){e.logger?.error(n.message);return}Rq(n)?(n.status===`INTERNAL_SERVER_ERROR`&&e.logger.error(n.status,n),i?.error(n.message)):e.logger?.error(n&&typeof n==`object`&&`name`in n?n.name:``,n)}}})};async function Jpe(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=ie(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./dist-BwJIqVtn.mjs`);n=i(r)(e)}return n.transaction||(C.warn(`Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.`),n.transaction=async e=>e(n)),n}async function Ype(e){return Jpe(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./kysely-adapter-B9j0_OfU.mjs`),{kysely:r,databaseType:i,transaction:a}=await t(e);if(!r)throw new D(`Failed to initialize database adapter`);return n(r,{type:i||`sqlite`,debugLogs:e.database&&`debugLogs`in e.database?e.database.debugLogs:!1,transaction:a})(e)})}function Xpe(e){let{indexesByTable:t,tables:n}=oe(e),r=/* @__PURE__ */ new Map,i={};for(let e in n){let t=n[e],a=t.fields,o={};Object.entries(a).forEach(([e,t])=>{let i=t.references,a=i?n[i.model]:void 0,s=i&&a?{...t,references:{...i,model:a.modelName}}:t;o[t.fieldName||e]=s,i&&r.set(s,{modelKey:i.model,fieldKey:i.field})}),i[t.modelName]?(i[t.modelName].fields={...i[t.modelName].fields,...o},t.disableMigrations&&(i[t.modelName].disableMigrations=!0)):i[t.modelName]={fields:o,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,n]of t)i[e]&&(i[e].indexes=n);return{schema:i,tables:n,referenceKeys:r}}const Zpe={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`int8`,`integer`,`bigint`,`smallint`,`numeric`,`real`,`double precision`],boolean:[`bool`,`boolean`],date:[`timestamptz`,`timestamp`,`date`],json:[`json`,`jsonb`]},mysql:{string:[`varchar`,`text`,`uuid`],number:[`integer`,`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`boolean`,`tinyint`],date:[`timestamp`,`datetime`,`date`],json:[`json`]},sqlite:{string:[`TEXT`],number:[`INTEGER`,`REAL`,`BIGINT`],boolean:[`INTEGER`,`BOOLEAN`],date:[`DATE`,`INTEGER`],json:[`TEXT`]},mssql:{string:[`varchar`,`nvarchar`,`uniqueidentifier`],number:[`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`bit`,`smallint`],date:[`datetime2`,`date`,`datetime`],json:[`varchar`,`nvarchar`]}};function SQ(e,t){return`${Se(e)}\u0000${Se(t)}`}function CQ(e,t){return`${e}\u0000${t}`}function wQ(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,n)=>e===t.columns[n])}function TQ(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function EQ(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[SQ(e.table,e.name),{columns:t.flatMap(e=>e.name===null?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>e.name!==null&&e.fullLength)}]}))}async function Qpe(e,n,r,i){if(i)return EQ(await i(r));let a;switch(n.type){case`sqlite`:a=(await t`
|
|
416
|
+
SELECT
|
|
417
|
+
tables.name AS "tableName",
|
|
418
|
+
index_list.name AS "indexName",
|
|
419
|
+
index_info.name AS "columnName",
|
|
420
|
+
index_list."unique" AS "isUnique",
|
|
421
|
+
index_list.partial AS "isPartial",
|
|
422
|
+
index_info.seqno AS "columnPosition"
|
|
423
|
+
FROM sqlite_master AS tables
|
|
424
|
+
INNER JOIN pragma_index_list(tables.name) AS index_list
|
|
425
|
+
INNER JOIN pragma_index_info(index_list.name) AS index_info
|
|
426
|
+
WHERE tables.type = 'table'
|
|
427
|
+
`.execute(e)).rows;break;case`postgres`:a=(await t`
|
|
428
|
+
SELECT
|
|
429
|
+
table_class.relname AS "tableName",
|
|
430
|
+
index_class.relname AS "indexName",
|
|
431
|
+
index_attribute.attname AS "columnName",
|
|
432
|
+
index_data.indisunique AS "isUnique",
|
|
433
|
+
index_data.indisvalid AS "isValid",
|
|
434
|
+
(index_data.indpred IS NOT NULL) AS "isPartial",
|
|
435
|
+
index_column.ordinality AS "columnPosition"
|
|
436
|
+
FROM pg_class AS table_class
|
|
437
|
+
INNER JOIN pg_namespace AS table_namespace
|
|
438
|
+
ON table_namespace.oid = table_class.relnamespace
|
|
439
|
+
INNER JOIN pg_index AS index_data
|
|
440
|
+
ON index_data.indrelid = table_class.oid
|
|
441
|
+
INNER JOIN pg_class AS index_class
|
|
442
|
+
ON index_class.oid = index_data.indexrelid
|
|
443
|
+
INNER JOIN LATERAL unnest(index_data.indkey)
|
|
444
|
+
WITH ORDINALITY AS index_column(attribute_number, ordinality)
|
|
445
|
+
ON TRUE
|
|
446
|
+
LEFT JOIN pg_attribute AS index_attribute
|
|
447
|
+
ON index_attribute.attrelid = table_class.oid
|
|
448
|
+
AND index_attribute.attnum = index_column.attribute_number
|
|
449
|
+
WHERE table_namespace.nspname = ${n.schema}
|
|
450
|
+
AND table_class.relkind = 'r'
|
|
451
|
+
AND index_column.ordinality <= index_data.indnkeyatts
|
|
452
|
+
`.execute(e)).rows;break;case`mysql`:a=(await t`
|
|
453
|
+
SELECT
|
|
454
|
+
table_name AS tableName,
|
|
455
|
+
index_name AS indexName,
|
|
456
|
+
column_name AS columnName,
|
|
457
|
+
non_unique AS nonUnique,
|
|
458
|
+
seq_in_index AS columnPosition,
|
|
459
|
+
sub_part AS prefixLength,
|
|
460
|
+
COALESCE(LOWER(comment) = 'disabled', FALSE) AS isDisabled
|
|
461
|
+
FROM information_schema.statistics
|
|
462
|
+
WHERE table_schema = DATABASE()
|
|
463
|
+
`.execute(e)).rows;break;case`mssql`:a=(await t`
|
|
464
|
+
SELECT
|
|
465
|
+
tables.name AS "tableName",
|
|
466
|
+
indexes.name AS "indexName",
|
|
467
|
+
columns.name AS "columnName",
|
|
468
|
+
indexes.is_unique AS "isUnique",
|
|
469
|
+
indexes.is_disabled AS "isDisabled",
|
|
470
|
+
indexes.is_hypothetical AS "isHypothetical",
|
|
471
|
+
indexes.has_filter AS "isPartial",
|
|
472
|
+
index_columns.key_ordinal AS "columnPosition"
|
|
473
|
+
FROM sys.indexes AS indexes
|
|
474
|
+
INNER JOIN sys.tables AS tables
|
|
475
|
+
ON indexes.object_id = tables.object_id
|
|
476
|
+
INNER JOIN sys.schemas AS table_schemas
|
|
477
|
+
ON table_schemas.schema_id = tables.schema_id
|
|
478
|
+
INNER JOIN sys.index_columns AS index_columns
|
|
479
|
+
ON index_columns.object_id = indexes.object_id
|
|
480
|
+
AND index_columns.index_id = indexes.index_id
|
|
481
|
+
INNER JOIN sys.columns AS columns
|
|
482
|
+
ON columns.object_id = index_columns.object_id
|
|
483
|
+
AND columns.column_id = index_columns.column_id
|
|
484
|
+
WHERE table_schemas.name = ${n.schema}
|
|
485
|
+
AND indexes.name IS NOT NULL
|
|
486
|
+
AND index_columns.key_ordinal > 0
|
|
487
|
+
`.execute(e)).rows}let o=/* @__PURE__ */ new Map;for(let e of a){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,n=e.indexName??e.index_name??e.INDEX_NAME??e.name,r=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!n)continue;let i=SQ(t,n),a=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=a===void 0?TQ(e.isUnique??e.is_unique):!TQ(a),c=Number(e.columnPosition??e.column_position??e.keyOrdinal??e.key_ordinal??e.ordinality??e.seqInIndex??e.seq_in_index??e.SEQ_IN_INDEX??e.seqno??0),l={fullLength:r!=null&&(e.prefixLength===void 0||e.prefixLength===null),name:r??null,position:c},u=TQ(e.isPartial),d=!TQ(e.isDisabled)&&!TQ(e.isHypothetical)&&(e.isValid===void 0||TQ(e.isValid)),f=o.get(i);o.set(i,f?{...f,columns:[...f.columns,l],partial:f.partial||u,valid:f.valid&&d}:{columns:[l],name:n,partial:u,table:t,unique:s,valid:d})}return EQ([...o.values()])}async function $pe(e,n){let r;switch(n.type){case`postgres`:case`sqlite`:return/* @__PURE__ */ new Map;case`mysql`:r=(await t`
|
|
488
|
+
SELECT
|
|
489
|
+
table_name AS tableName,
|
|
490
|
+
column_name AS columnName,
|
|
491
|
+
character_octet_length AS maxIndexBytes
|
|
492
|
+
FROM information_schema.columns
|
|
493
|
+
WHERE table_schema = DATABASE()
|
|
494
|
+
`.execute(e)).rows;break;case`mssql`:r=(await t`
|
|
495
|
+
SELECT
|
|
496
|
+
tables.name AS "tableName",
|
|
497
|
+
columns.name AS "columnName",
|
|
498
|
+
columns.max_length AS "maxIndexBytes"
|
|
499
|
+
FROM sys.columns AS columns
|
|
500
|
+
INNER JOIN sys.tables AS tables
|
|
501
|
+
ON tables.object_id = columns.object_id
|
|
502
|
+
INNER JOIN sys.schemas AS table_schemas
|
|
503
|
+
ON table_schemas.schema_id = tables.schema_id
|
|
504
|
+
WHERE table_schemas.name = ${n.schema}
|
|
505
|
+
`.execute(e)).rows}let i=/* @__PURE__ */ new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,n=e.columnName??e.COLUMN_NAME;if(!t||!n)continue;let r=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(CQ(t,n),{maxIndexBytes:r<0?null:r})}return i}function eme({columnBounds:e,dbType:t,existingColumns:n,fields:r,indexes:i,index:a,table:o}){let s=t===`mysql`?3072:1700,c=0;for(let s of a.columns){let l=r[s];if(l){if(l.type===`string`||Array.isArray(l.type)){if(!n.has(s)){let e=x({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let l=e.get(CQ(o,s));if(!l?.maxIndexBytes)throw new D(`Cannot create database index "${a.name}" on existing table "${o}" because column "${s}" is not bounded for ${t===`mysql`?`MySQL`:`SQL Server`}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);c+=l.maxIndexBytes}else c+=16}}if(c>s)throw new D(`Cannot create database index "${a.name}" on existing table "${o}" because its columns can exceed ${t===`mysql`?`MySQL`:`SQL Server`}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}var tme=class extends D{};function nme(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function rme(e){return!(e.unique&&e.required===!1)&&(e.type===`string`||e.type===`number`||e.type===`boolean`)&&e.defaultValue!==void 0&&e.defaultValue!==null&&typeof e.defaultValue!=`function`}async function ime(e,n,r){let i=e.selectFrom(r).select(t`1`.as(`present`));return(await(n===`mssql`?i.top(1):i.limit(1)).execute()).length>0}function ame(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=Zpe[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function DQ(e,{throwOnUnsafe:n=!0}={}){let{schema:r,tables:i,referenceKeys:o}=Xpe(e),d=ee(e.logger),f=[],p=e=>{if(n)throw new tme(e);f.push(e)},{kysely:m,databaseType:h,introspectIndexes:g,schemaName:v}=await u(e);h||=(d.warn(`Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.`),`sqlite`),m||(d.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let y=await m.introspection.getTables(),b,S=y;switch(h){case`postgres`:{let e=v??await a(m);b={type:`postgres`,schema:e},d.debug(`PostgreSQL migration: Using schema '${e}' (${v?`from database.schemaName`:`from search_path`})`);try{(await m.introspection.getSchemas()).some(({name:t})=>t===e)||(v?d.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):d.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){d.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}S=y.filter(t=>t.schema===e&&!t.isView&&!(`isForeign`in t&&t.isForeign)),d.debug(`Found ${S.length} table(s) in schema '${e}': ${S.map(e=>e.name).join(`, `)||`(none)`}`);break}case`mssql`:{let e=await c(m);b={type:`mssql`,schema:e},d.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),S=y.filter(t=>t.schema===e);break}case`mysql`:b={type:`mysql`};break;case`sqlite`:b={type:`sqlite`}}let C=await Qpe(m,b,y.map(e=>e.name),g),te=await $pe(m,b),w=ree(l(m,r),s(S)).filter(e=>e.kind===`unexpected-required-column`).map(e=>iee(e,`database`)),ne=[],T=[],re=[],ie=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(r)){if(t.disableMigrations)continue;let n=S.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=SQ(e,i),o=C.get(a);if(o){if(!wQ(o,r))throw new D(`Database index "${i}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if(h===`sqlite`||h===`postgres`){let t=[...C.values()].find(t=>Se(t.name)===Se(i)&&Se(t.table)!==Se(e));if(t)throw new D(`Database index name "${i}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=ie.get(a);if(s){if(!wQ({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},r))throw new D(`Database index name "${i}" identifies more than one index on table "${e}".`)}else n&&(h===`mysql`||h===`mssql`)&&eme({columnBounds:te,dbType:h,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),ie.set(a,r),re.push({table:e,index:r,name:i})}if(!n){let n=ne.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=ne.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?ne.push(r):ne[n].fields={...ne[n].fields,...t.fields}:ne.splice(i,0,r);continue}let r={};for(let[i,a]of Object.entries(t.fields)){let t=n.columns.find(e=>e.name===i);t?(a.required!==!1&&t.isNullable&&d.warn(`Column "${i}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!ame(t.dataType,a.type,h)&&d.warn(`Field ${i} in table ${e} has a different type in the database. Expected ${a.type} but got ${t.dataType}.`)):r[i]=a}Object.keys(r).length>0&&T.push({table:e,fields:r,order:t.order||1/0})}let ae=[];v&&ne.length>0&&ae.push(m.schema.createSchema(v).ifNotExists());let oe=e.advanced?.database?.generateId===`uuid`,se=e.advanced?.database?.generateId===`serial`;function ce(e,n,r){let i=e.type,a=h||`sqlite`,o={string:{sqlite:`text`,postgres:`text`,mysql:r?`varchar(${r})`:e.unique?`varchar(255)`:e.references?`varchar(36)`:e.sortable||e.index?`varchar(255)`:`text`,mssql:r?`varchar(${r})`:e.unique||e.sortable?`varchar(255)`:e.references?`varchar(36)`:`varchar(8000)`},boolean:{sqlite:`integer`,postgres:`boolean`,mysql:`boolean`,mssql:`smallint`},number:{sqlite:e.bigint?`bigint`:`integer`,postgres:e.bigint?`bigint`:`integer`,mysql:e.bigint?`bigint`:`integer`,mssql:e.bigint?`bigint`:`integer`},date:{sqlite:`date`,postgres:`timestamptz`,mysql:`timestamp(3)`,mssql:t`datetime2(3)`},json:{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},id:{postgres:se?t`integer GENERATED BY DEFAULT AS IDENTITY`:oe?`uuid`:`text`,mysql:se?`integer`:`varchar(36)`,mssql:se?`integer`:`varchar(36)`,sqlite:se?`integer`:`text`},foreignKeyId:{postgres:se?`integer`:oe?`uuid`:`text`,mysql:se?`integer`:`varchar(36)`,mssql:se?`integer`:`varchar(36)`,sqlite:se?`integer`:`text`},"string[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},"number[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`}};if(n===`id`||e.references?.field===`id`)return n===`id`?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return`text`;if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${n}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let le=cee({schema:i,usePlural:!1}),ue=lee({schema:i,usePlural:!1});function de(e){let t=e.references;if(!t)throw new D(`Cannot resolve a field without references.`);let n=o.get(e);if(!n)throw new D(`Missing migration reference metadata for "${t.model}.${t.field}".`);try{return`${le(n.modelKey)}.${ue({model:n.modelKey,field:n.fieldKey})}`}catch{return`${t.model}.${t.field}`}}let fe=[],pe=(e,t)=>{if(h!==`mysql`&&h!==`mssql`)return;let n=r[e];if(n)return x({columnName:t,dialect:h,fields:n.fields,indexes:n.indexes??[]})};if(T.length){let e=/* @__PURE__ */ new Map;for(let n of T)for(let[r,i]of Object.entries(n.fields)){let a=nme(i,h),o=rme(i);if(i.required!==!1&&!a&&!o){let t=e.get(n.table);if(t===void 0&&(t=await ime(m,h,n.table),e.set(n.table,t)),t){let e=i.type===`string`?` For a text column, every existing row ends up with the same empty string.`:``;p(`Cannot add required column "${r}" to populated table "${n.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let s=ce(i,r,pe(n.table,r)),c=m.schema.alterTable(n.table);if(i.index||i.unique){let e=_(n.table,r,i.unique??!1),t=m.schema.createIndex(e).on(n.table).columns([r]);i.unique&&(t=t.unique(),i.required===!1&&h===`mssql`&&(t=t.where(r,`is not`,null)),i.required!==!1&&i.defaultValue!==void 0&&i.defaultValue!==null&&typeof i.defaultValue!=`function`&&d.warn(`Adding unique column "${r}" to existing table "${n.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),fe.push(t)}let l=c.addColumn(r,s,e=>(e=i.required===!1?e:e.notNull(),i.references&&(e=e.references(de(i)).onDelete(i.references.onDelete||`cascade`)),a?e=h===`mysql`?e.defaultTo(t`CURRENT_TIMESTAMP(3)`):e.defaultTo(t`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo(typeof i.defaultValue==`boolean`&&(h===`sqlite`||h===`mssql`)?+!!i.defaultValue:i.defaultValue)),e));ae.push(l)}}if(ne.length)for(let e of ne){let n=ce({type:se?`number`:`string`},`id`),r=m.schema.createTable(e.table).addColumn(`id`,n,e=>se?h===`postgres`||h===`sqlite`?e.primaryKey().notNull():h===`mssql`?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull():oe&&h===`postgres`?e.primaryKey().defaultTo(t`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull());for(let[n,i]of Object.entries(e.fields)){let a=ce(i,n,pe(e.table,n));if(r=r.addColumn(n,a,e=>(e=i.required===!1?e:e.notNull(),i.references&&(e=e.references(de(i)).onDelete(i.references.onDelete||`cascade`)),i.unique&&(e=e.unique()),i.type===`date`&&typeof i.defaultValue==`function`&&(h===`postgres`||h===`mysql`||h===`mssql`)&&(e=h===`mysql`?e.defaultTo(t`CURRENT_TIMESTAMP(3)`):e.defaultTo(t`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let t=m.schema.createIndex(_(e.table,n,!1)).on(e.table).columns([n]);fe.push(t)}}ae.push(r)}for(let{table:e,index:t,name:n}of re){let r=m.schema.createIndex(n).on(e).columns([...t.columns]);t.unique&&(r=r.unique()),fe.push(r)}for(let e of fe)ae.push(e);async function me(){try{for(let e of ae)await e.execute()}finally{ae.length&&e.database&&oee(e.database)}}async function he(){return ae.map(e=>e.compile().sql).join(`;
|
|
506
|
+
|
|
507
|
+
`)+`;`}return{toBeCreated:ne,toBeAdded:T,toBeAddedIndexes:re,unsafeChanges:f,schemaProblems:w,runMigrations:me,compileMigrations:he}}function ome(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function sme(e){return e?e.split(`,`).map(e=>{e=e.trim();let t=e.indexOf(`:`);if(t===-1)throw new D(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let n=parseInt(e.slice(0,t),10);if(!Number.isInteger(n)||n<0)throw new D(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let r=e.slice(t+1).trim();if(!r)throw new D(`Empty secret value for version ${n} in BETTER_AUTH_SECRETS.`);return{version:n,value:r}}):null}function cme(e,t){if(e.length===0)throw new D("`secrets` array must contain at least one entry.");let n=/* @__PURE__ */ new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new D(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new D(`Empty secret value for version ${e} in \`secrets\`.`);if(n.has(e))throw new D(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);n.add(e)}let r=e[0];r.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${r.version}) should be at least 32 characters long for adequate security.`),ome(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function lme(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(parseInt(String(t.version),10),t.value);return{keys:n,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&t!==`better-auth-secret-12345678901234567890`?t:void 0}}async function ume(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let n=e.socialProviders?.[t];if(!n)return{};let r=typeof n==`function`?await n():n;return{id:t,mapProfileToUser:!!r.mapProfileToUser,disableDefaultScope:!!r.disableDefaultScope,disableIdTokenSignIn:!!r.disableIdTokenSignIn,disableImplicitSignUp:r.disableImplicitSignUp,disableSignUp:r.disableSignUp,getUserInfo:!!r.getUserInfo,overrideUserInfoOnSignIn:!!r.overrideUserInfoOnSignIn,prompt:r.prompt,verifyIdToken:!!r.verifyIdToken,scope:r.scope,refreshAccessToken:!!r.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}function dme(){let e=S.npm_config_user_agent;if(!e)return;let t=e.split(` `)[0],n=t.lastIndexOf(`/`),r=t.substring(0,n);return{name:r===`npminstall`?`cnpm`:r,version:t.substring(n+1)}}function fme(){return S.CI!==`false`&&(`BUILD_ID`in S||`BUILD_NUMBER`in S||`CI`in S||`CI_APP_ID`in S||`CI_BUILD_ID`in S||`CI_BUILD_NUMBER`in S||`CI_NAME`in S||`CONTINUOUS_INTEGRATION`in S||`RUN_ID`in S)}function pme(){return typeof Deno<`u`?{name:`deno`,version:Deno?.version?.deno??null}:typeof Bun<`u`?{name:`bun`,version:Bun?.version??null}:typeof process<`u`&&process?.versions?.node?{name:`node`,version:process.versions.node??null}:{name:`edge`,version:null}}function mme(){return tee(`NODE_ENV`)===`production`?`production`:fme()?`ci`:v()?`test`:`development`}async function OQ(e){let t=await FU(`SHA-256`).digest(e);return he.encode(t)}const hme=e=>f(`a-z`,`A-Z`,`0-9`)(e||32);let kQ;async function AQ(){if(kQ)return kQ;try{let e=process.cwd();if(!e)return;let t=await At.readFile(dt.join(e,`package.json`),`utf-8`);return kQ=JSON.parse(t),kQ}catch{}}async function jQ(e){if(kQ)return kQ.dependencies?.[e]||kQ.devDependencies?.[e]||kQ.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error(`no-cwd`);let n=dt.join(t,`node_modules`,e,`package.json`),r=await At.readFile(n,`utf-8`);return JSON.parse(r).version||await MQ(e)||void 0}catch{}return MQ(e)}async function MQ(e){let t=await AQ();if(t)return{...t.dependencies,...t.devDependencies,...t.peerDependencies}[e]}async function gme(){return(await AQ())?.name}async function _me(){try{let e=_t.cpus();return{deploymentVendor:vme(),systemPlatform:_t.platform(),systemRelease:_t.release(),systemArchitecture:_t.arch(),cpuCount:e.length,cpuModel:e.length?e[0].model:null,cpuSpeed:e.length?e[0].speed:null,memory:_t.totalmem(),isWSL:await Cme(),isDocker:await PQ(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}function vme(){let e=process.env,t=(...t)=>t.some(t=>!!e[t]);return t(`CF_PAGES`,`CF_PAGES_URL`,`CF_ACCOUNT_ID`)||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`?`cloudflare`:t(`VERCEL`,`VERCEL_URL`,`VERCEL_ENV`)?`vercel`:t(`NETLIFY`,`NETLIFY_URL`)?`netlify`:t(`RENDER`,`RENDER_URL`,`RENDER_INTERNAL_HOSTNAME`,`RENDER_SERVICE_ID`)?`render`:t(`AWS_LAMBDA_FUNCTION_NAME`,`AWS_EXECUTION_ENV`,`LAMBDA_TASK_ROOT`)?`aws`:t(`GOOGLE_CLOUD_FUNCTION_NAME`,`GOOGLE_CLOUD_PROJECT`,`GCP_PROJECT`,`K_SERVICE`)?`gcp`:t(`AZURE_FUNCTION_NAME`,`FUNCTIONS_WORKER_RUNTIME`,`WEBSITE_INSTANCE_ID`,`WEBSITE_SITE_NAME`)?`azure`:t(`DENO_DEPLOYMENT_ID`,`DENO_REGION`)?`deno-deploy`:t(`FLY_APP_NAME`,`FLY_REGION`,`FLY_ALLOC_ID`)?`fly-io`:t(`RAILWAY_STATIC_URL`,`RAILWAY_ENVIRONMENT_NAME`)?`railway`:t(`DYNO`,`HEROKU_APP_NAME`)?`heroku`:t(`DO_DEPLOYMENT_ID`,`DO_APP_NAME`,`DIGITALOCEAN`)?`digitalocean`:t(`KOYEB`,`KOYEB_DEPLOYMENT_ID`,`KOYEB_APP_NAME`)?`koyeb`:null}let NQ;async function yme(){try{return Dt.statSync(`/.dockerenv`),!0}catch{return!1}}async function bme(){try{return Dt.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}async function PQ(){return NQ===void 0&&(NQ=await yme()||await bme()),NQ}let FQ;const xme=async()=>{try{return Dt.statSync(`/run/.containerenv`),!0}catch{return!1}};async function Sme(){return FQ===void 0&&(FQ=await xme()||await PQ()),FQ}async function Cme(){try{return process.platform===`linux`&&(_t.release().toLowerCase().includes(`microsoft`)||Dt.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`))?!await Sme():!1}catch{return!1}}let IQ=null;async function LQ(e){if(IQ)return IQ;let t=await gme();return t?(IQ=await OQ(e?e+t:t),IQ):e?(IQ=await OQ(e),IQ):(IQ=hme(32),IQ)}async function wme(){for(let[e,t]of Object.entries({pg:`postgresql`,mysql:`mysql`,mariadb:`mariadb`,sqlite3:`sqlite`,"better-sqlite3":`sqlite`,"@prisma/client":`prisma`,mongoose:`mongodb`,mongodb:`mongodb`,"drizzle-orm":`drizzle`})){let n=await jQ(e);if(n)return{name:t,version:n}}}async function Tme(){for(let[e,t]of Object.entries({next:`next`,nuxt:`nuxt`,"react-router":`react-router`,astro:`astro`,"@sveltejs/kit":`sveltekit`,"solid-start":`solid-start`,"tanstack-start":`tanstack-start`,hono:`hono`,express:`express`,elysia:`elysia`,expo:`expo`})){let n=await jQ(e);if(n)return{name:t,version:n}}}const Eme=async function(){};async function Dme(e,t){let n=e.telemetry?.debug||ne(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=y.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:Eme};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(C.error):r&&(n?C.info(`telemetry event`,JSON.stringify(e,null,2)):await BX(r,{method:`POST`,body:e}).catch(C.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(ne(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!v())})(),o;return a&&(o=await LQ(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await ume(e,t),runtime:pme(),database:await wme(),framework:await Tme(),environment:mme(),systemInfo:await _me(),packageManager:dme()},anonymousId:o})),{publish:async t=>{a&&(o||=await LQ(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function Ome(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function kme(e,t){let n=e===`better-auth-secret-12345678901234567890`;if(!v()){if(n&&ae)throw new D("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!e)throw new D("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");e.length<32&&t.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),Ome(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function Ame(e,t,n){let r=GW(t);r||(t=cY(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=cY(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=TY(t),o=ee(t.logger),s=WH(t.baseURL);if(WH(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||e.length===0)throw new D(`baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).`)}let c=s?void 0:BH(typeof t.baseURL==`string`?t.baseURL:void 0,t.basePath);!c&&!s&&o.warn(`[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly.`),e.id===`memory`&&t.advanced?.database?.generateId===!1&&o.error(`[better-auth] Misconfiguration detected.
|
|
508
|
+
You are using the memory DB with generateId: false.
|
|
509
|
+
This will cause no id to be generated for any model.
|
|
510
|
+
Most of the features of Better Auth will not work correctly.`);let l=t.secrets??sme(S.BETTER_AUTH_SECRETS),u=t.secret||S.BETTER_AUTH_SECRET||S.AUTH_SECRET||``,d,f;l?(cme(l,o),d=l[0].value,f=lme(l,u)):(d=u||`better-auth-secret-12345678901234567890`,kme(d,o),f=d),t={...t,secret:d,baseURL:s?t.baseURL:c?new URL(c).origin:``,basePath:t.basePath||`/api/auth`,plugins:i.concat(a)},Kpe(t,o);let p=t.advanced?.ipAddress?.trustedProxies;if(p&&p.length>0){let e=xJ(p);e.length>0&&o.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(`, `)}. Each entry must be an IP address or CIDR range.`)}let m=aq(t),h=ie(t),g=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let n=typeof t==`function`?await t():t;if(n==null||n.enabled===!1)return null;n.clientId||o.warn(`Social provider ${e} is missing clientId or clientSecret`);let r=eQ[e](n);return r.disableImplicitSignUp=n.disableImplicitSignUp,r}))).filter(e=>e!==null),_=({model:e,size:n})=>{if(typeof t.advanced?.generateId==`function`)return t.advanced.generateId({model:e,size:n});let r=t?.advanced?.database?.generateId;return typeof r==`function`?r({model:e,size:n}):r===`uuid`?crypto.randomUUID():r===`serial`||r===!1?!1:ge(n)},{publish:y}=await Dme(t,{adapter:e.id,database:typeof t.database==`function`?`adapter`:n(t.database)}),b=new Set(t.plugins.map(e=>e.id)),x=e=>t.plugins.find(t=>t.id===e)??null,C=e=>b.has(e),te=await EY(t),w=await jY(t),ne={appName:t.appName||`Better Auth`,baseURL:c||``,version:se(),socialProviders:g,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:h,trustedOrigins:te,trustedProviders:w,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>Qq(e,n,t))},sessionConfig:{updateAge:t.session?.updateAge===void 0?86400:t.session.updateAge,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(()=>{let e=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300;return r&&e?(o.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):e===!1||e===void 0?!1:e===!0?{enabled:!0,updateAge:Math.floor(n*.2)}:{enabled:!0,updateAge:e.updateAge===void 0?Math.floor(n*.2):e.updateAge}})()},secret:d,secretConfig:f,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??ae,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?`secondary-storage`:`memory`)},authCookies:m,logger:o,generateId:_,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||MU,verify:t.emailAndPassword?.password?.verify||NU,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:bpe},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:iY(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:_}),createAuthCookie:iq(t),async runMigrations(){throw new D(`runMigrations will be set by the specific init implementation`)},publishTelemetry:y,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck===void 0?!!v():t.advanced.disableOriginCheck,runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{o.error(`Failed to run background task:`,e)})):await e}catch(e){o.error(`Failed to run background task:`,e)}},getPlugin:x,hasPlugin:C},T=wY(ne);return mG(T)&&await T,ne.checkSchema=ot(ne.adapter),ne.explicitSchemaCheck=aee(ne.adapter),ne}const jme=async e=>{let t=await Ame(await Ype(e),e,e=>o(e)||`unknown`);return t.runMigrations=async function(){if(!e.database||`updateMany`in e.database)throw new D(`Database is not provided or it's an adapter. Migrations are only supported with a database instance.`);let{runMigrations:t}=await DQ(e);await t()},t},Mme=(e,t)=>{let n=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;if(!e.checkSchema&&t!==!1){let n=t===!0?`warn`:`debug`;e.logger[n](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`)}let n=e.checkSchema?.();return n&&n.catch(t=>{e.logger.error(t instanceof see?t.message:`Could not validate the database schema. Check your database connection.`)}),e}),{api:r}=xQ(n,e),i=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),a=async t=>{let r=await n,i=r.options.basePath||`/api/auth`,a;if(WH(e.baseURL))a=await kY(r,t,OY(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=BH(void 0,i,t,void 0,r.options.advanced?.trustedProxyHeaders);if(!n)throw new D(`Could not get base URL from request. Please provide a valid base URL.`);a.baseURL=n,a.options={...r.options,baseURL:VH(n)||void 0},e=a.options}a.trustedOrigins=await EY(e,t),a.trustedProviders=await jY(e,t)}let{handler:o}=qpe(a,e);return EH(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...Y}}},Nme=e=>Mme(e,jme),RQ=CH({INVALID_METADATA_TYPE:`metadata must be an object or undefined`,REFILL_AMOUNT_AND_INTERVAL_REQUIRED:`refillAmount is required when refillInterval is provided`,REFILL_INTERVAL_AND_AMOUNT_REQUIRED:`refillInterval is required when refillAmount is provided`,USER_BANNED:`User is banned`,UNAUTHORIZED_SESSION:`Unauthorized or invalid session`,KEY_NOT_FOUND:`API Key not found`,KEY_DISABLED:`API Key is disabled`,KEY_EXPIRED:`API Key has expired`,USAGE_EXCEEDED:`API Key has reached its usage limit`,KEY_NOT_RECOVERABLE:`API Key is not recoverable`,EXPIRES_IN_IS_TOO_SMALL:`The expiresIn is smaller than the predefined minimum value.`,EXPIRES_IN_IS_TOO_LARGE:`The expiresIn is larger than the predefined maximum value.`,INVALID_REMAINING:`The remaining count is either too large or too small.`,INVALID_PREFIX_LENGTH:`The prefix length is either too large or too small.`,INVALID_NAME_LENGTH:`The name length is either too large or too small.`,METADATA_DISABLED:`Metadata is disabled.`,RATE_LIMIT_EXCEEDED:`Rate limit exceeded.`,NO_VALUES_TO_UPDATE:`No values to update.`,KEY_DISABLED_EXPIRATION:`Custom key expiration values are disabled.`,INVALID_API_KEY:`Invalid API key.`,INVALID_USER_ID_FROM_API_KEY:`The user id from the API key is invalid.`,INVALID_REFERENCE_ID_FROM_API_KEY:`The reference id from the API key is invalid.`,INVALID_API_KEY_GETTER_RETURN_TYPE:`API Key getter returned an invalid key type. Expected string.`,SERVER_ONLY_PROPERTY:`The property you're trying to set can only be set from the server auth instance only.`,FAILED_TO_UPDATE_API_KEY:`Failed to update API key`,NAME_REQUIRED:`API Key name is required.`,ORGANIZATION_ID_REQUIRED:`Organization ID is required for organization-owned API keys.`,USER_NOT_MEMBER_OF_ORGANIZATION:`You are not a member of the organization that owns this API key.`,INSUFFICIENT_API_KEY_PERMISSIONS:`You do not have permission to perform this action on organization API keys.`,NO_DEFAULT_API_KEY_CONFIGURATION_FOUND:`No default api-key configuration found.`,ORGANIZATION_PLUGIN_REQUIRED:`Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin.`});async function zQ(e,t,n){let r=e.length;if(r===0)return[];let{signal:i}=n;if(i?.aborted)throw i.reason;let a=Math.floor(n.concurrency),o=Math.min(r,a>=1?a:1),s=Array(r),c=0,l=!1;return await Promise.all(Array.from({length:o},async()=>{for(;!l&&c<r;){if(i?.aborted)throw i.reason;let n=c++;try{s[n]=await t(e[n],n)}catch(e){throw l=!0,e}}})),s}const Pme={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Fme=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,BQ={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},Ime=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Lme(e){return e instanceof Date&&!isNaN(e.getTime())}function Rme(e){let t=Ime.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return Lme(f)?f:null}function zme(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in BQ)return BQ[s];if(!Fme.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(Pme).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t)r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);else{if(a&&typeof t==`string`){let e=Rme(t);if(e)return e}return i?i(e,t):t}})}catch(t){if(n)throw t;return e}}function Bme(e,t={strict:!0}){return zme(e,t)}function VQ(e){return e==null?null:typeof e==`object`?e:ye(e)}function HQ(e){return e!=null&&typeof e==`string`}async function Vme(e,t,n){if(n.storage!==`database`&&!n.fallbackToDatabase)return;let r=t.filter(e=>HQ(e.metadata));if(r.length===0)return;let i=r.map(async t=>{let n=VQ(t.metadata);try{await e.context.adapter.update({model:`apikey`,where:[{field:`id`,value:t.id}],update:{metadata:n}})}catch(n){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,n)}});await Promise.all(i)}async function UQ(e,t,n){let r=VQ(t.metadata);if(HQ(t.metadata)&&(n.storage===`database`||n.fallbackToDatabase))try{await e.context.adapter.update({model:`apikey`,where:[{field:`id`,value:t.id}],update:{metadata:r}})}catch(n){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,n)}return r}function WQ(e){return`api-key:${e}`}function GQ(e){return`api-key:by-id:${e}`}function KQ(e){return`api-key:by-ref:${e}`}function Hme(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),expiresAt:e.expiresAt?.toISOString()??null,lastRefillAt:e.lastRefillAt?.toISOString()??null,lastRequest:e.lastRequest?.toISOString()??null})}function qQ(e){if(!e||typeof e!=`string`)return null;try{let t=JSON.parse(e);return{...t,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),expiresAt:t.expiresAt?new Date(t.expiresAt):null,lastRefillAt:t.lastRefillAt?new Date(t.lastRefillAt):null,lastRequest:t.lastRequest?new Date(t.lastRequest):null}}catch{return null}}function JQ(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function YQ(e){if(e.expiresAt){let t=Date.now(),n=new Date(e.expiresAt).getTime(),r=Math.floor((n-t)/1e3);if(r>0)return r}}async function XQ(e,t,n){let r=WQ(t);return qQ(await n.get(r))}async function ZQ(e,t,n){let r=GQ(t);return qQ(await n.get(r))}const QQ=/* @__PURE__ */ new Map;function Ume(e,t){let n=(QQ.get(e)??Promise.resolve()).then(t,t).finally(()=>{QQ.get(e)===n&&QQ.delete(e)});return QQ.set(e,n),n}async function $Q(e,t,n){await Ume(t,async()=>{let r=await e.get(t),i=[];if(r&&typeof r==`string`)try{i=JSON.parse(r)}catch{i=[]}else Array.isArray(r)&&(i=r);let a=n(i);a.length===0?await e.delete(t):await e.set(t,JSON.stringify(a))})}async function e$(e,t,n,r,i){let a=Hme(t),o=KQ(t.referenceId);i.fallbackToDatabase?await Promise.all([n.set(WQ(t.key),a,r),n.set(GQ(t.id),a,r),n.delete(o)]):(await Promise.all([n.set(WQ(t.key),a,r),n.set(GQ(t.id),a,r)]),await $Q(n,o,e=>e.includes(t.id)?e:[...e,t.id]))}async function Wme(e,t,n,r){let i=KQ(t.referenceId);r.fallbackToDatabase?await Promise.all([n.delete(WQ(t.key)),n.delete(GQ(t.id)),n.delete(i)]):await Promise.all([n.delete(WQ(t.key)),n.delete(GQ(t.id)),$Q(n,i,e=>e.filter(e=>e!==t.id))])}async function t$(e,t,n){let r=JQ(e,n);if(n.storage===`database`)return await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]});if(n.storage===`secondary-storage`&&n.fallbackToDatabase){if(r){let n=await XQ(e,t,r);if(n)return n}let i=await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]});return i&&r&&await e$(e,i,r,YQ(i),n),i}return n.storage===`secondary-storage`?r?await XQ(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]})}async function n$(e,t,n){let r=JQ(e,n);if(n.storage===`database`)return await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]});if(n.storage===`secondary-storage`&&n.fallbackToDatabase){if(r){let n=await ZQ(e,t,r);if(n)return n}let i=await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]});return i&&r&&await e$(e,i,r,YQ(i),n),i}return n.storage===`secondary-storage`?r?await ZQ(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]})}async function r$(e,t,n){let r=JQ(e,n),i=YQ(t);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await e$(e,t,r,i,n)}}async function i$(e,t,n){let r=JQ(e,n);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await Wme(e,t,r,n)}}function a$(e,t,n,r,i){let a=[...e];if(t){let e=n||`asc`;a.sort((n,r)=>{let i=n[t],a=r[t];return i==null&&a==null?0:i==null?e===`asc`?-1:1:a==null?e===`asc`?1:-1:i<a?e===`asc`?-1:1:i>a?e===`asc`?1:-1:0})}return i!==void 0&&(a=a.slice(i)),r!==void 0&&(a=a.slice(0,r)),a}async function o$(e,t,n,r){let i=JQ(e,n),{limit:a,offset:o,sortBy:s,sortDirection:c}=r||{};if(n.storage===`database`){let[n,r]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);return{apiKeys:n,total:r}}if(n.storage===`secondary-storage`&&n.fallbackToDatabase){let r=KQ(t);if(i){let t=await i.get(r),n=[];if(t&&typeof t==`string`)try{n=JSON.parse(t)}catch{n=[]}else Array.isArray(t)&&(n=t);if(n.length>0){let t=(await zQ(n,t=>ZQ(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:a$(t,s,c,a,o),total:t.length}}}let[l,u]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);if(i&&l.length>0){await zQ(l,t=>e$(e,t,i,YQ(t),n),{concurrency:10});let t=l.map(e=>e.id);await i.set(r,JSON.stringify(t))}return{apiKeys:l,total:u}}if(n.storage===`secondary-storage`){if(!i)return{apiKeys:[],total:0};let n=KQ(t),r=await i.get(n),l=[];if(r&&typeof r==`string`)try{l=JSON.parse(r)}catch{return{apiKeys:[],total:0}}else if(Array.isArray(r))l=r;else return{apiKeys:[],total:0};let u=(await zQ(l,t=>ZQ(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:a$(u,s,c,a,o),total:u.length}}let[l,u]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);return{apiKeys:l,total:u}}function Gme(e){let t=e.context;if(`orgOptions`in t&&t.orgOptions)return t.orgOptions;let n=t.getPlugin?.(`organization`);return n&&`options`in n?n.options:null}async function s$(e,t,n,r){let i=Gme(e);if(!i){let e=RQ.ORGANIZATION_PLUGIN_REQUIRED;throw E.from(`INTERNAL_SERVER_ERROR`,e)}let a=await e.context.adapter.findOne({model:`member`,where:[{field:`userId`,value:t},{field:`organizationId`,value:n}]});if(!a){let e=RQ.USER_NOT_MEMBER_OF_ORGANIZATION;throw E.from(`FORBIDDEN`,e)}if(!await Kme(e,a.role,n,r,i)){let e=RQ.INSUFFICIENT_API_KEY_PERMISSIONS;throw E.from(`FORBIDDEN`,e)}return a}async function Kme(e,t,n,r,i){let{hasPermission:a}=await import(`./organization-B_0UJJOj.mjs`);try{return await a({role:t,options:i,permissions:{apiKey:[r]},organizationId:n,allowCreatorAllPermissions:!0},e)}catch{return!1}}const c$=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function qme(e){return e instanceof E||e instanceof E||e?.name===`APIError`}const Jme=A({configId:k().meta({description:`The configuration ID to use for the API key. If not provided, the default configuration will be used.`}).optional(),name:k().meta({description:`Name of the Api Key`}).optional(),expiresIn:Le().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable().default(null),prefix:k().meta({description:`Prefix of the Api Key`}).regex(/^[a-zA-Z0-9_-]+$/,{message:`Invalid prefix format, must be alphanumeric and contain only underscores and hyphens.`}).optional(),remaining:Le().meta({description:`Remaining number of requests. Server side only`}).min(0).optional().nullable().default(null),metadata:et().optional(),refillAmount:Le().meta({description:`Amount to refill the remaining count of the Api Key. server-only. Eg: 100`}).min(1).optional(),refillInterval:Le().meta({description:`Interval to refill the Api Key in milliseconds. server-only. Eg: 1000`}).optional(),rateLimitTimeWindow:Le().meta({description:"The duration in milliseconds where each request is counted. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 1000"}).optional(),rateLimitMax:Le().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),rateLimitEnabled:Je().meta({description:`Whether the key has rate limiting enabled. server-only. Eg: true`}).optional(),permissions:ze(k(),Be(k())).meta({description:`Permissions of the Api Key.`}).optional(),userId:JW().meta({description:`User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"`}).optional(),organizationId:JW().meta({description:`Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'`}).optional()});function Yme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:r}){return X(`/api-key/create`,{method:`POST`,body:Jme,metadata:{openapi:{description:`Create a new API key for a user`,responses:{200:{description:`API key created successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`Unique identifier of the API key`},createdAt:{type:`string`,format:`date-time`,description:`Creation timestamp`},updatedAt:{type:`string`,format:`date-time`,description:`Last update timestamp`},name:{type:`string`,nullable:!0,description:`Name of the API key`},prefix:{type:`string`,nullable:!0,description:`Prefix of the API key`},start:{type:`string`,nullable:!0,description:`Starting characters of the key (if configured)`},key:{type:`string`,description:`The full API key (only returned on creation)`},enabled:{type:`boolean`,description:`Whether the key is enabled`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiration timestamp`},referenceId:{type:`string`,description:`ID of the reference owning the key`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`Last refill timestamp`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`Last request timestamp`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Metadata associated with the key`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum requests in time window`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`Rate limit time window in milliseconds`},remaining:{type:`number`,nullable:!0,description:`Remaining requests`},refillAmount:{type:`number`,nullable:!0,description:`Amount to refill`},refillInterval:{type:`number`,nullable:!0,description:`Refill interval in milliseconds`},rateLimitEnabled:{type:`boolean`,description:`Whether rate limiting is enabled`},requestCount:{type:`number`,description:`Current request count in window`},permissions:{type:`object`,nullable:!0,additionalProperties:{type:`array`,items:{type:`string`}},description:`Permissions associated with the key`}},required:[`id`,`createdAt`,`updatedAt`,`key`,`enabled`,`referenceId`,`rateLimitEnabled`,`requestCount`]}}}}}}}},async n=>{let{configId:i,name:a,expiresIn:o,prefix:s,remaining:c,metadata:l,refillAmount:u,refillInterval:d,permissions:f,rateLimitMax:p,rateLimitTimeWindow:m,rateLimitEnabled:h}=n.body,g=f$(n.context,t,i),_=g.customKeyGenerator||e,v=await HJ(n,{disableCookieCache:!0}),y=n.request||n.headers;if(y&&(u!==void 0||d!==void 0||p!==void 0||m!==void 0||h!==void 0||f!==void 0||c!==null))throw E.from(`BAD_REQUEST`,RQ.SERVER_ONLY_PROPERTY);if(n.request&&n.body.userId!==void 0)throw E.from(`UNAUTHORIZED`,RQ.UNAUTHORIZED_SESSION);let b=g.references??`user`,x;if(b===`organization`){let e=n.body.organizationId;if(!e){let e=RQ.ORGANIZATION_ID_REQUIRED;throw E.from(`BAD_REQUEST`,e)}let t=v?.user.id||n.body.userId;if(!t)throw E.from(`UNAUTHORIZED`,RQ.UNAUTHORIZED_SESSION);await s$(n,t,e,`create`),x=e}else if(y){if(!v?.user.id){let e=RQ.UNAUTHORIZED_SESSION;throw E.from(`UNAUTHORIZED`,e)}x=v.user.id}else{let e=n.body.userId,t=v?.user.id;if(!t&&!e||v&&e&&t!==e){let e=RQ.UNAUTHORIZED_SESSION;throw E.from(`UNAUTHORIZED`,e)}x=t||e}if(l){if(g.enableMetadata===!1)throw E.from(`BAD_REQUEST`,RQ.METADATA_DISABLED);if(typeof l!=`object`)throw E.from(`BAD_REQUEST`,RQ.INVALID_METADATA_TYPE)}if(u&&!d){let e=RQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(d&&!u){let e=RQ.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(o){if(g.keyExpiration.disableCustomExpiresTime===!0){let e=RQ.KEY_DISABLED_EXPIRATION;throw E.from(`BAD_REQUEST`,e)}let e=o/86400;if(g.keyExpiration.minExpiresIn>e){let e=RQ.EXPIRES_IN_IS_TOO_SMALL;throw E.from(`BAD_REQUEST`,e)}if(g.keyExpiration.maxExpiresIn<e){let e=RQ.EXPIRES_IN_IS_TOO_LARGE;throw E.from(`BAD_REQUEST`,e)}}if(s&&(s.length<g.minimumPrefixLength||s.length>g.maximumPrefixLength))throw E.from(`BAD_REQUEST`,RQ.INVALID_PREFIX_LENGTH);if(a){if(a.length<g.minimumNameLength||a.length>g.maximumNameLength)throw E.from(`BAD_REQUEST`,RQ.INVALID_NAME_LENGTH)}else if(g.requireName)throw E.from(`BAD_REQUEST`,RQ.NAME_REQUIRED);r(n.context);let S=await _({length:g.defaultKeyLength,prefix:s||g.defaultPrefix}),ee=g.disableKeyHashing?S:await _$(S),C=null;g.startingCharactersConfig.shouldStore&&(C=S.substring(0,g.startingCharactersConfig.charactersLength));let te=g.permissions?.defaultPermissions?typeof g.permissions.defaultPermissions==`function`?await g.permissions.defaultPermissions(x,n):g.permissions.defaultPermissions:void 0,w=f?JSON.stringify(f):te?JSON.stringify(te):void 0,ne={configId:g.configId??`default`,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,name:a??null,prefix:s??g.defaultPrefix??null,start:C,key:ee,enabled:!0,expiresAt:o?c$(o,`sec`):g.keyExpiration.defaultExpiresIn?c$(g.keyExpiration.defaultExpiresIn,`sec`):null,referenceId:x,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:p??g.rateLimit.maxRequests??null,rateLimitTimeWindow:m??g.rateLimit.timeWindow??null,remaining:c===null?c:c??u??null,refillAmount:u??null,refillInterval:d??null,rateLimitEnabled:h===void 0?g.rateLimit.enabled??!0:h,requestCount:0,permissions:w};l&&(ne.metadata=l);let T;if(g.storage===`secondary-storage`&&g.fallbackToDatabase)T=await n.context.adapter.create({model:v$,data:ne}),await r$(n,T,g);else if(g.storage===`secondary-storage`){let e=n.context.generateId({model:`apikey`})||ge();T={...ne,id:e},await r$(n,T,g)}else T=await n.context.adapter.create({model:v$,data:ne});return n.json({...T,key:S,metadata:l??null,permissions:T.permissions?ye(T.permissions):null})})}function Xme({deleteAllExpiredApiKeys:e}){return X.serverOnly({method:`POST`},async t=>{try{await e(t.context,!0)}catch(e){return t.context.logger.error(`[API KEY PLUGIN] Failed to delete expired API keys:`,e),t.json({success:!1,error:e})}return t.json({success:!0,error:null})})}const Zme=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:k().meta({description:`The id of the Api Key`})});function Qme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/delete`,{method:`POST`,body:Zme,use:[WJ],metadata:{openapi:{description:`Delete an existing API key`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{keyId:{type:`string`,description:`The id of the API key to delete`}},required:[`keyId`]}}}},responses:{200:{description:`API key deleted successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the API key was successfully deleted`}},required:[`success`]}}}}}}}},async t=>{let{configId:r,keyId:i}=t.body,a=t.context.session;if(a.user.banned===!0)throw E.from(`UNAUTHORIZED`,RQ.USER_BANNED);let o=f$(t.context,e,r),s=null;if(s=await n$(t,i,o),!s||!m$(s.configId,o.configId))throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let c=f$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await s$(t,a.user.id,s.referenceId,`delete`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);try{c.storage===`secondary-storage`&&c.fallbackToDatabase?(await i$(t,s,c),await t.context.adapter.delete({model:v$,where:[{field:`id`,value:s.id}]})):c.storage===`database`?await t.context.adapter.delete({model:v$,where:[{field:`id`,value:s.id}]}):await i$(t,s,c)}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}return n(t.context),t.json({success:!0})})}const $me=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),id:k().meta({description:`The id of the Api Key`})});function ehe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/get`,{method:`GET`,query:$me,use:[WJ],metadata:{openapi:{description:`Retrieve an existing API key by ID`,responses:{200:{description:`API key retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}}}}}}}},async t=>{let{configId:r,id:i}=t.query,a=t.context.session,o=f$(t.context,e,r),s=null;if(s=await n$(t,i,o),!s||!m$(s.configId,o.configId))throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let c=f$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await s$(t,a.user.id,s.referenceId,`read`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);n(t.context);let l=await UQ(t,s,c),{key:u,...d}=s;return t.json({...d,metadata:l,permissions:d.permissions?ye(d.permissions):null})})}function the(e){return e.storage===`database`?`database`:e.customStorage?`custom:${e.configId??`default`}`:e.fallbackToDatabase?`secondary-storage-with-fallback`:`secondary-storage`}const nhe=A({configId:k().meta({description:`Filter by configuration ID. If not provided, returns keys from all configurations.`}).optional(),organizationId:k().meta({description:`Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys.`}).optional(),limit:YW().int().nonnegative().meta({description:`The number of API keys to return`}).optional(),offset:YW().int().nonnegative().meta({description:`The offset to start from`}).optional(),sortBy:k().meta({description:`The field to sort by (e.g., createdAt, name, expiresAt)`}).optional(),sortDirection:Ze([`asc`,`desc`]).meta({description:`The direction to sort by`}).optional()}).optional();function rhe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/list`,{method:`GET`,use:[WJ],query:nhe,metadata:{openapi:{description:`List all API keys for the authenticated user or for a specific organization`,responses:{200:{description:`API keys retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{apiKeys:{type:`array`,items:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}},total:{type:`number`,description:`Total number of API keys`},limit:{type:`number`,nullable:!0,description:`The limit used for pagination`},offset:{type:`number`,nullable:!0,description:`The offset used for pagination`}},required:[`apiKeys`,`total`]}}}}}}}},async t=>{let r=t.context.session,i=t.query?.configId,a=t.query?.organizationId,o=t.query?.limit==null?void 0:Number(t.query.limit),s=t.query?.offset==null?void 0:Number(t.query.offset);a&&await s$(t,r.user.id,a,`read`);let c=a??r.user.id,l=a?`organization`:`user`,u=[];if(i){let{apiKeys:n}=await o$(t,c,f$(t.context,e,i),{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection});u=n}else{let n=/* @__PURE__ */ new Map;for(let t of e){let e=the(t);n.has(e)||n.set(e,t)}let r=await Promise.all([...n.values()].map(e=>o$(t,c,e,{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection}))),i=/* @__PURE__ */ new Set;for(let{apiKeys:e}of r)for(let t of e)i.has(t.id)||(i.add(t.id),u.push(t))}let d=u.filter(t=>(e.find(e=>p$(t.configId)?p$(e.configId):e.configId===t.configId)?.references??`user`)===l&&t.referenceId===c);i&&(d=d.filter(e=>m$(e.configId,i)));let f=d.length,p=d;s!==void 0&&(p=p.slice(s)),o!==void 0&&(p=p.slice(0,o)),n(t.context);let m=p.map(e=>{let{key:t,...n}=e;return{...n,metadata:VQ(e.metadata),permissions:n.permissions?ye(n.permissions):null}}),h=e.find(e=>e.storage===`database`||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(Vme(t,p,h)),t.json({apiKeys:m,total:f,limit:o,offset:s})})}const ihe=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:k().meta({description:`The id of the Api Key`}),userId:JW().meta({description:`The id of the user which the api key belongs to. server-only. Eg: "some-user-id"`}).optional(),name:k().meta({description:`The name of the key`}).optional(),enabled:Je().meta({description:`Whether the Api Key is enabled or not`}).optional(),remaining:Le().meta({description:`The number of remaining requests`}).min(1).optional(),refillAmount:Le().meta({description:`The refill amount`}).optional(),refillInterval:Le().meta({description:`The refill interval`}).optional(),metadata:et().optional(),expiresIn:Le().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable(),rateLimitEnabled:Je().meta({description:`Whether the key has rate limiting enabled.`}).optional(),rateLimitTimeWindow:Le().meta({description:`The duration in milliseconds where each request is counted. server-only. Eg: 1000`}).optional(),rateLimitMax:Le().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),permissions:ze(k(),Be(k())).meta({description:`Update the permissions on the API Key. server-only.`}).optional().nullable()});function ahe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/update`,{method:`POST`,body:ihe,metadata:{openapi:{description:`Update an existing API key by ID`,responses:{200:{description:`API key updated successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}}}}}}}},async t=>{let{configId:r,keyId:i,expiresIn:a,enabled:o,metadata:s,refillAmount:c,refillInterval:l,remaining:u,name:d,permissions:f,rateLimitEnabled:p,rateLimitTimeWindow:m,rateLimitMax:h}=t.body,g=await HJ(t,{disableCookieCache:!0}),_=t.request||t.headers,v=_&&!g?null:g?.user||{id:t.body.userId};if(!v?.id||g&&t.body.userId&&g?.user.id!==t.body.userId)throw E.from(`UNAUTHORIZED`,RQ.UNAUTHORIZED_SESSION);if(_&&(c!==void 0||l!==void 0||h!==void 0||m!==void 0||p!==void 0||u!==void 0||f!==void 0))throw E.from(`BAD_REQUEST`,RQ.SERVER_ONLY_PROPERTY);let y=f$(t.context,e,r),b=null;if(b=await n$(t,i,y),!b||!m$(b.configId,y.configId))throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let x=f$(t.context,e,b.configId);if((x.references??`user`)===`organization`)await s$(t,v.id,b.referenceId,`update`);else if(b.referenceId!==v.id)throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let S={};if(d!==void 0){if(d.length<x.minimumNameLength||d.length>x.maximumNameLength)throw E.from(`BAD_REQUEST`,RQ.INVALID_NAME_LENGTH);S.name=d}if(o!==void 0&&(S.enabled=o),a!==void 0){if(x.keyExpiration.disableCustomExpiresTime===!0)throw E.from(`BAD_REQUEST`,RQ.KEY_DISABLED_EXPIRATION);if(a!==null){let e=a/86400;if(e<x.keyExpiration.minExpiresIn)throw E.from(`BAD_REQUEST`,RQ.EXPIRES_IN_IS_TOO_SMALL);if(e>x.keyExpiration.maxExpiresIn)throw E.from(`BAD_REQUEST`,RQ.EXPIRES_IN_IS_TOO_LARGE)}S.expiresAt=a?c$(a,`sec`):null}if(s!==void 0&&x.enableMetadata===!0){if(typeof s!=`object`)throw E.from(`BAD_REQUEST`,RQ.INVALID_METADATA_TYPE);S.metadata=s}if(u!==void 0&&(S.remaining=u),c!==void 0||l!==void 0){if(c!==void 0&&l===void 0)throw E.from(`BAD_REQUEST`,RQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(l!==void 0&&c===void 0)throw E.from(`BAD_REQUEST`,RQ.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);S.refillAmount=c,S.refillInterval=l}if(p!==void 0&&(S.rateLimitEnabled=p),m!==void 0&&(S.rateLimitTimeWindow=m),h!==void 0&&(S.rateLimitMax=h),f!==void 0&&(S.permissions=JSON.stringify(f)),Object.keys(S).length===0)throw E.from(`BAD_REQUEST`,RQ.NO_VALUES_TO_UPDATE);let ee=b;try{if(x.storage===`secondary-storage`&&x.fallbackToDatabase){let e=await t.context.adapter.update({model:v$,where:[{field:`id`,value:b.id}],update:S});e&&(await r$(t,e,x),ee=e)}else if(x.storage===`database`){let e=await t.context.adapter.update({model:v$,where:[{field:`id`,value:b.id}],update:S});e&&(ee=e)}else{let e={...b,...S,updatedAt:/* @__PURE__ */ new Date};await r$(t,e,x),ee=e}}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}n(t.context);let C=await UQ(t,ee,x),{key:te,...w}=ee;return t.json({...w,metadata:C,permissions:w.permissions?ye(w.permissions):null})})}function l$(e,t){let n=/* @__PURE__ */ new Date,r=e.lastRequest,i=e.rateLimitTimeWindow,a=e.rateLimitMax;if(t.rateLimit.enabled===!1||e.rateLimitEnabled===!1)return{type:`skip`,lastRequest:n};if(i===null||a===null)return{type:`skip`,lastRequest:null};if(r===null)return{type:`start`,now:n};let o=n.getTime()-new Date(r).getTime();return o>i?{type:`reset`,now:n,windowStart:new Date(n.getTime()-i)}:e.requestCount>=a?{type:`deny`,message:RQ.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(i-o)}:{type:`increment`,now:n,max:a,windowStart:new Date(n.getTime()-i)}}async function u$({key:e,ctx:t,lookupOpts:n,configurations:r,schema:i,permissions:a,expectedConfigId:o,runCustomValidator:s}){let c=n.disableKeyHashing?e:await _$(e),l=await t$(t,c,n);if(!l||o!==void 0&&!m$(l.configId,o))throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);let u=f$(t.context,r,l.configId);if(s&&u.customAPIKeyValidator&&!await u.customAPIKeyValidator({ctx:t,key:e}))throw E.from(`UNAUTHORIZED`,RQ.KEY_NOT_FOUND);if(l.enabled===!1)throw E.from(`UNAUTHORIZED`,RQ.KEY_DISABLED);if(l.expiresAt&&Date.now()>new Date(l.expiresAt).getTime()){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await i$(t,l,u),await t.context.adapter.delete({model:v$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await i$(t,l,u):await t.context.adapter.delete({model:v$,where:[{field:`id`,value:l.id}]})};throw u.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),E.from(`UNAUTHORIZED`,RQ.KEY_EXPIRED)}if(a){let e=l.permissions?ye(l.permissions):null;if(!e||!uee(e).authorize(a).success)throw E.from(`UNAUTHORIZED`,RQ.KEY_NOT_FOUND)}if(l.remaining===0&&l.refillAmount===null){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await i$(t,l,u),await t.context.adapter.delete({model:v$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await i$(t,l,u):await t.context.adapter.delete({model:v$,where:[{field:`id`,value:l.id}]})};throw u.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),E.from(`TOO_MANY_REQUESTS`,RQ.USAGE_EXCEEDED)}return{apiKey:u.storage===`database`||u.storage===`secondary-storage`&&u.fallbackToDatabase?await ohe({ctx:t,apiKey:l,opts:u,hashedKey:c}):await che({ctx:t,apiKey:l,opts:u,hashedKey:c}),opts:u}}async function ohe({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t;t.remaining!==null&&(i=await she(e,t)),i=await d$(e,i,n);let a=await e.context.adapter.update({model:v$,where:[{field:`id`,value:i.id}],update:{updatedAt:/* @__PURE__ */ new Date}});if(!a)throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);return n.storage===`secondary-storage`&&n.fallbackToDatabase&&await r$(e,a,n),a}async function she(e,t){let n=/* @__PURE__ */ new Date,{refillInterval:r,refillAmount:i}=t;if(r&&i){let a=new Date(t.lastRefillAt??t.createdAt).getTime();if(n.getTime()-a>r){let r=await e.context.adapter.incrementOne({model:v$,where:[{field:`id`,value:t.id},{field:`lastRefillAt`,value:t.lastRefillAt}],increment:{},set:{remaining:i-1,lastRefillAt:n}});if(r)return r}}let a=await e.context.adapter.incrementOne({model:v$,where:[{field:`id`,value:t.id},{field:`remaining`,operator:`gt`,value:0}],increment:{remaining:-1}});if(!a)throw E.from(`TOO_MANY_REQUESTS`,RQ.USAGE_EXCEEDED);return a}async function d$(e,t,n){let r=l$(t,n);if(r.type===`deny`)throw new E(`TOO_MANY_REQUESTS`,{message:r.message,code:`RATE_LIMITED`,details:{tryAgainIn:r.tryAgainIn}});if(r.type===`skip`)return r.lastRequest===null?t:await e.context.adapter.update({model:`apikey`,where:[{field:`id`,value:t.id}],update:{lastRequest:r.lastRequest}})??t;if(r.type===`increment`){let i=await e.context.adapter.incrementOne({model:v$,where:[{field:`id`,value:t.id},{field:`lastRequest`,operator:`gt`,value:r.windowStart},{field:`requestCount`,operator:`lt`,value:r.max}],increment:{requestCount:1},set:{lastRequest:r.now}});if(i)return i;let a=await e.context.adapter.findOne({model:v$,where:[{field:`id`,value:t.id}]});if(!a)throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);return d$(e,a,n)}let i=r.type===`reset`?{field:`lastRequest`,operator:`lte`,value:r.windowStart}:{field:`lastRequest`,operator:`eq`,value:null},a=await e.context.adapter.incrementOne({model:v$,where:[{field:`id`,value:t.id},i],increment:{},set:{requestCount:1,lastRequest:r.now}});if(a)return a;let o=await e.context.adapter.findOne({model:v$,where:[{field:`id`,value:t.id}]});if(!o)throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);return d$(e,o,n)}async function che({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t.remaining,a=t.lastRefillAt;if(i!==null){let e=Date.now(),{refillInterval:n,refillAmount:r}=t,o=new Date(a??t.createdAt).getTime();if(n&&r&&e-o>n&&(i=r,a=/* @__PURE__ */ new Date),i===0)throw E.from(`TOO_MANY_REQUESTS`,RQ.USAGE_EXCEEDED);i--}let o={...lhe(t,n),remaining:i,lastRefillAt:a,updatedAt:/* @__PURE__ */ new Date},s=async()=>{let t=await t$(e,r,n);if(!t)return null;let i={...t,...o};return await r$(e,i,n),i};if(n.deferUpdates)return e.context.runInBackground(s().catch(t=>{e.context.logger.error(`Failed to update API key:`,t)})),{...t,...o};let c=await s();if(!c)throw E.from(`INTERNAL_SERVER_ERROR`,RQ.FAILED_TO_UPDATE_API_KEY);return c}function lhe(e,t){let n=l$(e,t);switch(n.type){case`deny`:throw new E(`TOO_MANY_REQUESTS`,{message:n.message,code:`RATE_LIMITED`,details:{tryAgainIn:n.tryAgainIn}});case`skip`:return n.lastRequest===null?{}:{lastRequest:n.lastRequest};case`start`:case`reset`:return{lastRequest:n.now,requestCount:1};case`increment`:return{lastRequest:n.now,requestCount:e.requestCount+1}}}const uhe=A({configId:k().meta({description:`Configuration ID to scope verification to. When omitted, the key is validated against its own configuration.`}).optional(),key:k().meta({description:`The key to verify`}),permissions:ze(k(),Be(k())).meta({description:`The permissions to verify.`}).optional()});function dhe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X.serverOnly({method:`POST`,body:uhe},async r=>{let{configId:i,key:a}=r.body,o=f$(r.context,e,i);if(i!==void 0&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:RQ.INVALID_API_KEY,code:`KEY_NOT_FOUND`},key:null});let s=null,c;try{let l=await u$({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:o,configurations:e,schema:t,expectedConfigId:i,runCustomValidator:i===void 0});s=l.apiKey,c=l.opts,c.deferUpdates&&r.context.runInBackground(n(r.context).catch(e=>{r.context.logger.error(`Failed to delete expired API keys:`,e)}))}catch(e){return r.context.logger.error(`Failed to validate API key:`,e),qme(e)?r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null}):r.json({valid:!1,error:{message:RQ.INVALID_API_KEY,code:`INVALID_API_KEY`},key:null})}let{key:l,...u}=s??{key:1,permissions:void 0},d=null;return s&&(d=await UQ(r,s,c)),u.permissions=u.permissions?ye(u.permissions):null,r.json({valid:!0,error:null,key:s===null?null:{...u,metadata:d}})})}function f$(e,t,n){let r=()=>{let n=t.find(e=>!e.configId||e.configId==="default");if(!n){e.logger.error("No default api-key configuration found. Either provide an api-key configuration with configId 'default' or provide a configuration with no `configId` set.");let t=RQ.NO_DEFAULT_API_KEY_CONFIGURATION_FOUND;throw E.from(`BAD_REQUEST`,t)}return{...n,configId:`default`}};return n?t.find(e=>e.configId===n)??r():r()}function p$(e){return!e||e==="default"}function m$(e,t){return p$(e)&&p$(t)?!0:e===t}let h$=null;async function g$(e,t=!1){h$&&!t&&(/* @__PURE__ */ new Date()).getTime()-h$.getTime()<1e4||(h$=/* @__PURE__ */ new Date,await e.adapter.deleteMany({model:v$,where:[{field:`expiresAt`,operator:`lt`,value:/* @__PURE__ */ new Date},{field:`expiresAt`,operator:`ne`,value:null}]}).catch(t=>{e.logger.error(`Failed to delete expired API keys:`,t)}))}function fhe({defaultKeyGenerator:e,configurations:t,schema:n}){return{createApiKey:Yme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),verifyApiKey:dhe({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),getApiKey:ehe({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),updateApiKey:ahe({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),deleteApiKey:Qme({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),listApiKeys:rhe({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),deleteAllExpiredApiKeys:Xme({deleteAllExpiredApiKeys:g$})}}const phe=({defaultRateLimitMax:e,defaultTimeWindow:t})=>({apikey:{fields:{configId:{type:`string`,required:!0,defaultValue:`default`,input:!1,index:!0},name:{type:`string`,required:!1,input:!1},start:{type:`string`,required:!1,input:!1},referenceId:{type:`string`,required:!0,input:!1,index:!0},prefix:{type:`string`,required:!1,input:!1},key:{type:`string`,required:!0,input:!1,index:!0},refillInterval:{type:`number`,required:!1,input:!1},refillAmount:{type:`number`,required:!1,input:!1},lastRefillAt:{type:`date`,required:!1,input:!1},enabled:{type:`boolean`,required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:`boolean`,required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:`number`,required:!1,input:!1,defaultValue:t},rateLimitMax:{type:`number`,required:!1,input:!1,defaultValue:e},requestCount:{type:`number`,required:!1,input:!1,defaultValue:0},remaining:{type:`number`,required:!1,input:!1},lastRequest:{type:`date`,required:!1,input:!1},expiresAt:{type:`date`,required:!1,input:!1},createdAt:{type:`date`,required:!0,input:!1},updatedAt:{type:`date`,required:!0,input:!1},permissions:{type:`string`,required:!1,input:!1},metadata:{type:`string`,required:!1,input:!0,transform:{input(e){return JSON.stringify(e)},output(e){return e?Bme(e):null}}}}}}),_$=async e=>{let t=await FU(`SHA-256`).digest(new TextEncoder().encode(e));return me.encode(new Uint8Array(t),{padding:!1})},v$=`apikey`;function mhe(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new D(`configId is required for each API key configuration in the api-key plugin.`);let t=e.map(e=>e.configId);if(new Set(t).size!==t.length)throw new D(`configId must be unique for each API key configuration in the api-key plugin.`)}let n=t??{schema:Array.isArray(e)?void 0:e?.schema},r=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??`x-api-key`,defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??`database`,rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],i=fG(phe({defaultRateLimitMax:(r.length===1?r[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(r.length===1?r[0]?.rateLimit.timeWindow:void 0)??864e5}),n.schema),a=async e=>{let t=ZH(e.length,`a-z`,`A-Z`);return`${e.prefix||``}${t}`};function o(e,t){if(t.customAPIKeyGetter)return t.customAPIKeyGetter(e);if(Array.isArray(t.apiKeyHeaders)){for(let n of t.apiKeyHeaders){let t=e.headers?.get(n);if(t)return t}return null}return e.headers?.get(t.apiKeyHeaders)??null}function s(e){for(let t of r){if(!t.enableSessionForAPIKeys)continue;let n=o(e,t);if(n)return{key:n,config:t}}return null}let c=fhe({defaultKeyGenerator:a,configurations:r,schema:i});return{id:`api-key`,version:`1.7.12`,$ERROR_CODES:RQ,hooks:{before:[{matcher:e=>!!s(e),handler:Hq(async e=>{let{key:t,config:n}=s(e);if(typeof t!=`string`)throw E.from(`BAD_REQUEST`,RQ.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:t}))throw E.from(`FORBIDDEN`,RQ.INVALID_API_KEY);let{apiKey:a}=await u$({key:t,ctx:e,lookupOpts:n,configurations:r,schema:i,expectedConfigId:n.configId}),o=g$(e.context).catch(t=>{e.context.logger.error(`Failed to delete expired API keys:`,t)});if(n.deferUpdates&&e.context.runInBackground(o),(n.references??`user`)!==`user`){let e=RQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let c=await e.context.internalAdapter.findUserById(a.referenceId);if(!c){let e=RQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let l={user:c,session:{id:a.id,token:t,userId:a.referenceId,userAgent:e.request?.headers.get(`user-agent`)??null,ipAddress:e.request?wJ(e.request,e.context.options):null,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,expiresAt:a.expiresAt||c$(e.context.options.session?.expiresIn||604800,`ms`)}};return e.context.session=l,e.path===`/get-session`?l:{context:e}})}]},endpoints:{createApiKey:c.createApiKey,verifyApiKey:c.verifyApiKey,getApiKey:c.getApiKey,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,listApiKeys:c.listApiKeys,deleteAllExpiredApiKeys:c.deleteAllExpiredApiKeys},schema:i}}function y$(e){return e?.jwks?.keyPairConfig?.alg??`EdDSA`}const b$=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await TH(e)).findMany({model:`jwks`}),getLatestKey:async n=>{let r=/* @__PURE__ */ new Date,i=e=>!e.expiresAt||e.expiresAt>r;return t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]:(await(await TH(e)).findMany({model:`jwks`}))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},getKeyById:async(n,r)=>t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.find(e=>e.id===r):await(await TH(e)).findOne({model:`jwks`,where:[{field:`id`,value:r}]})??void 0,getLatestKeyByAlg:async(n,r)=>{let i=t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await TH(e)).findMany({model:`jwks`});if(!i)return;let a=y$(t),o=/* @__PURE__ */ new Date;return i.filter(e=>e.alg===r||e.alg==null&&a===r).filter(e=>!e.expiresAt||e.expiresAt>o).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},createJwk:async(n,r)=>t?.adapter?.createJwk?await t.adapter.createJwk(r,n):await(await TH(e)).create({model:`jwks`,data:{...r,createdAt:/* @__PURE__ */ new Date}})});function x$(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+_G(e)}async function hhe(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await Wde(t,{...n,extractable:!0});return{publicWebKey:await iI(r),privateWebKey:await iI(i),alg:t,cfg:n}}async function S$(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await hhe(t),o=a&&`crv`in a?a.crv:void 0,s=typeof n.crv==`string`?n.crv:void 0,c=o??s,l=JSON.stringify(r),u=!t?.jwks?.disablePrivateKeyEncryption,d={alg:i,...c?{crv:c}:{},publicKey:JSON.stringify(n),privateKey:u?JSON.stringify(await VW({key:e.context.secretConfig,data:l})):l,createdAt:/* @__PURE__ */ new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1e3)}:{}};return await b$(e.context.adapter,t).createJwk(e,d)}async function C$(e,t,n){if(t?.jwt?.sign)return null;let r=b$(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new D(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let e=y$(t);if((i.alg??e)!==n.signingAlgorithm)throw new D(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${e}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await r.getLatestKeyByAlg(e,n.signingAlgorithm),!i){let r=y$(t),a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await S$(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new D(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${r}"; additional algs configured via keyPairConfigs: ${e}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let n=y$(t);i=await r.getLatestKeyByAlg(e,n)??await r.getLatestKey(e)}if(!i||i.expiresAt&&i.expiresAt</* @__PURE__ */ new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new D(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await S$(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await HW({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new D(`Failed to decrypt private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either clean up your JWKS or disable private key encryption.`)}),o=i.alg??y$(t),s=await fI(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function w$(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=x$(n?.jwt?.expirationTime??`15m`,a??i);o??=s;let c=r.nbf,l=typeof e.context.options.baseURL==`string`?e.context.options.baseURL:``,u=r.iss,d=n?.jwt?.issuer??l,f=r.aud,p=n?.jwt?.audience??l;if((!(u??d)||!(f??p))&&e.context.logger.warn("[better-auth] The JWT plugin signed a JWT without an issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options."),n?.jwt?.sign){let e={...r,iat:a,exp:o,nbf:c,iss:u??d,aud:f??p};return n.jwt.sign(e,t.header,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm})}let{alg:m,kid:h,privateKey:g}=t.resolvedKey??await C$(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new tI(r).setProtectedHeader({...t.header,alg:m,kid:h}).setExpirationTime(o).setIssuer(u??d).setAudience(f??p);return a&&_.setIssuedAt(a),r.sub&&_.setSubject(r.sub),r.nbf&&_.setNotBefore(r.nbf),r.jti&&_.setJti(r.jti),await _.sign(g)}async function T$(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await w$(e,{options:t,payload:{iat:Math.floor(Date.now()/1e3),...n,sub:await t?.jwt?.getSubject?.(e.context.session)??e.context.session.user.id}})}function E$(e){let t=e.context.options.baseURL;return typeof t==`string`?t||`better-auth:session-cache`:e.context.baseURL||`better-auth:session-cache`}async function ghe(e,t,n){let r=pI(t).kid;if(!r)return e.context.logger.debug(`Cookie-cache JWT missing kid in header`),null;let i=await b$(e.context.adapter,n).getAllKeys(e);if(!i?.length)return e.context.logger.debug(`No JWKS keys available for cookie-cache JWT`),null;let a=i.find(e=>e.id===r);if(!a)return e.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${r}`),null;let o=a.alg??y$(n);return{alg:o,publicKey:await fI(JSON.parse(a.publicKey),o)}}async function _he(e,t,n,r){let i=await C$(e,r);if(!i)throw new D("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new tI({...t,sid:t.session.token}).setProtectedHeader({alg:i.alg,kid:i.kid,typ:`better-auth.session-cache+jwt`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).setIssuer(E$(e)).setAudience(`better-auth:session-cache`).setSubject(t.user.id).sign(i.privateKey)}async function vhe(e,t,n){try{if(pI(t).typ!==`better-auth.session-cache+jwt`)return null;let r=await ghe(e,t,n);if(!r)return null;let{payload:i}=await $F(t,r.publicKey,{...AG({issuer:E$(e)}),algorithms:[r.alg]}),a=jG(i);return a?{payload:a,expiresAt:a.exp?a.exp*1e3:Date.now()}:null}catch(t){return e.context.logger.debug(`Cookie-cache JWT verification failed`,t),null}}function yhe(e){return{sign:(t,n,r)=>_he(t,n,r,e),verify:(t,n)=>vhe(t,n,e)}}const bhe={jwks:{fields:{publicKey:{type:`string`,required:!0},privateKey:{type:`string`,required:!0},createdAt:{type:`date`,required:!0},expiresAt:{type:`date`,required:!1},alg:{type:`string`,required:!1},crv:{type:`string`,required:!1}}}};async function xhe(e,t){let n=gH();try{let r=e.split(`.`);if(r.length!==3)return null;let i=new TextDecoder().decode(he.decode(r[0])),a=JSON.parse(i).kid;if(!a)return n.context.logger.debug(`JWT missing kid in header`),null;let o=await b$(n.context.adapter,t).getAllKeys(n);if(!o||o.length===0)return n.context.logger.debug(`No JWKS keys available`),null;let s=o.find(e=>e.id===a);if(!s)return n.context.logger.debug(`No JWKS key found for kid: ${a}`),null;let c=JSON.parse(s.publicKey),l=s.alg??y$(t),u=await fI(c,l),d=typeof n.context.options.baseURL==`string`?n.context.options.baseURL:void 0,f=t?.jwt?.issuer??d,p=t?.jwt?.audience??d;(!f||!p)&&n.context.logger.warn("[better-auth] The JWT plugin is verifying a JWT without checking its issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");let{payload:m}=await $F(e,u,{issuer:f,audience:p,algorithms:[l]});return!m.sub||!m.aud?null:m}catch(e){return n.context.logger.debug(`JWT verification failed`,e),null}}const She=A({payload:ze(k(),et()),overrideOptions:ze(k(),et()).optional()}),Che=A({token:k(),issuer:k().optional()}),whe=e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new D(`options.jwks.remoteUrl must be set when using options.jwt.sign`);if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new D(`options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata`);let t=e?.jwks?.jwksPath??`/jwks`;if(typeof t!=`string`||t.length===0||!t.startsWith(`/`)||t.includes(`..`))throw new D(`options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'`);return{id:`jwt`,version:`1.7.12`,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!==`jwt`)throw new D('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new D("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let n=e.jwks?.gracePeriod,r=t.options.session.cookieCache.maxAge||300;return n!==void 0&&r>n&&t.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${r}s) exceeds the JWT plugin JWKS grace period (${n}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...t.sessionConfig,cookieCacheSigner:yhe(e)}}}},endpoints:{getJwks:X(t,{method:`GET`,metadata:{openapi:{operationId:`getJSONWebKeySet`,description:`Get the JSON Web Key Set`,responses:{200:{description:`JSON Web Key Set retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{keys:{type:`array`,description:`Array of public JSON Web Keys`,items:{type:`object`,properties:{kid:{type:`string`,description:`Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk`},kty:{type:`string`,description:`Key type (e.g., 'RSA', 'EC', 'OKP')`},alg:{type:`string`,description:`Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')`},use:{type:`string`,description:`Intended use of the public key (e.g., 'sig' for signature)`,enum:[`sig`],nullable:!0},n:{type:`string`,description:`Modulus for RSA keys (base64url-encoded)`,nullable:!0},e:{type:`string`,description:`Exponent for RSA keys (base64url-encoded)`,nullable:!0},crv:{type:`string`,description:`Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')`,nullable:!0},x:{type:`string`,description:`X coordinate for elliptic curve keys (base64url-encoded)`,nullable:!0},y:{type:`string`,description:`Y coordinate for elliptic curve keys (base64url-encoded)`,nullable:!0}},required:[`kid`,`kty`,`alg`]}}},required:[`keys`]}}}}}}}},async t=>{if(e?.jwks?.remoteUrl)throw new E(`NOT_FOUND`);let n=b$(t.context.adapter,e),r=await n.getAllKeys(t);if((!r||r?.length===0)&&(await S$(t,e),r=await n.getAllKeys(t)),!r?.length)throw new D(`No key sets found. Make sure you have a key in your database.`);let i=Date.now(),a=(e?.jwks?.gracePeriod??2592e3)*1e3,o=r.filter(e=>!e.expiresAt||e.expiresAt.getTime()+a>i),s=e?.jwks?.keyPairConfig,c=s&&`crv`in s?s.crv:void 0;return t.json({keys:o.map(t=>({alg:t.alg??y$(e),crv:t.crv??c,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:X(`/token`,{method:`GET`,requireHeaders:!0,use:[WJ],metadata:{openapi:{operationId:`getJSONWebToken`,description:`Get a JWT token`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async t=>{let n=await T$(t,e);return t.json({token:n})}),signJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{}}},body:She},async t=>{let n=await w$(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:n})}),verifyJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{},response:{}}},body:Che},async t=>{let n=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,r=await xhe(t.body.token,n);return t.json({payload:r})})},hooks:{after:[{matcher(e){return e.path===`/get-session`},handler:Hq(async t=>{if(e?.disableSettingJwtHeader)return;let n=t.context.session||t.context.newSession;if(n&&n.session){let n=await T$(t,e),r=t.context.responseHeaders?.get(`access-control-expose-headers`)||``,i=new Set(r.split(`,`).map(e=>e.trim()).filter(Boolean));i.add(`set-auth-jwt`),t.setHeader(`set-auth-jwt`,n),t.setHeader(`Access-Control-Expose-Headers`,Array.from(i).join(`, `))}})}]},schema:fG(bhe,e?.schema)}};var D$=Object.defineProperty,O$=(e,t)=>{let n={};for(var r in e)D$(n,r,{get:e[r],enumerable:!0});return t||D$(n,Symbol.toStringTag,{value:`Module`}),n};const k$=`ba_iat`,A$=`ba_pl`,j$=`ba_param`;function M$(e){let t=new URLSearchParams,n=[...e.entries()].sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:+(t>r));for(let[e,r]of n)t.append(e,r);return t}function The(e){e.delete(j$);let t=[.../* @__PURE__ */ new Set([...e.keys(),j$])].sort();for(let n of t)e.append(j$,n)}function Ehe(e){let t=new URLSearchParams(e).get(k$);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}const Dhe=[`authorization_code`,`client_credentials`,`refresh_token`],N$=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],Ohe=[`none`,...N$],khe=new Set(Ohe);function P$(e,t){if(!(t.trim().length>0))throw new D(`OAuth Provider extension ${e} cannot be empty`)}function F$(e,t){P$(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new D(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function Ahe(e){F$(`grant type`,e)}function jhe(e){if(P$(`token_endpoint_auth_method`,e),khe.has(e))throw new D(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function Mhe(e){if(F$(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new D(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function Nhe(e){let t=Object.keys(e.grants??{});for(let e of t)Ahe(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){jhe(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new D(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)Mhe(t),r.push(t)}let i=(e.clientDiscovery?Array.isArray(e.clientDiscovery)?e.clientDiscovery:[e.clientDiscovery]:[]).map(e=>e.id);for(let e of i)P$(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function I$(e,t){let n=/* @__PURE__ */ new Set;for(let r of t){if(n.has(r))throw new D(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function L$(e){let t=(e??[]).map(Nhe);I$(`grant type`,t.flatMap(e=>e.grantTypes)),I$(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),I$(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),I$(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function R$(e){return e.extensions??[]}function z$(e){return R$(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function Phe(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new D(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];L$(i),n.options.extensions=i}function Fhe(e){return R$(e).flatMap(e=>Object.keys(e.grants??{}))}function B$(e){return Array.from(/* @__PURE__ */ new Set([...e.grantTypes??Dhe,...Fhe(e)]))}function Ihe(e,t){for(let n of R$(e)){let e=n.grants?.[t];if(e)return e}}function V$(e){return R$(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function H$(e,t){return Array.from(/* @__PURE__ */ new Set([...t?.includeNone?[`none`]:[],...N$,...V$(e)]))}function U$(e,t){return t?V$(e).includes(t):!1}function Lhe(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of R$(e)){let e=n.clientAuthentication??{};for(let[n,r]of Object.entries(e))if((r.assertionTypes??[n]).includes(t))return{method:n,strategy:r}}}function W$(e,t,n,r){let i={...r};for(let a of R$(t)){let o=a.metadata?.({ctx:e,opts:t,type:n,document:r});for(let[e,t]of Object.entries(o??{}))e in i||(i[e]=t)}return i}async function G$(e,t){let n={};for(let r of R$(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?C.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function Rhe(e,t){return G$(e,e=>e.claims?.accessToken?.(t))}function zhe(e,t){return G$(e,e=>e.claims?.idToken?.(t))}function Bhe(e,t){return G$(e,e=>e.claims?.userInfo?.(t))}function Vhe(e){return R$(e).some(e=>e.claims?.userInfo)}function Hhe(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function Uhe(){let e=/* @__PURE__ */ new Map;return{get(t){let n=e.get(t);if(n){if(n.expiresAt&&n.expiresAt</* @__PURE__ */ new Date)e.delete(t);else return n}},set(t,n){e.set(t,n)}}}const K$=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new D(`jwt_config`);return t},Whe=/* @__PURE__ */ new Set([dP.code,cP.code,uP.code]);function q$(e){return e instanceof QN&&!Whe.has(e.code)}function J$(e){if(e!=null){if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;if(typeof e==`number`){if(!Number.isFinite(e))return;let t=new Date(e);return Number.isFinite(t.getTime())?t:void 0}if(typeof e==`string`){let t=e.trim();if(!t.length)return;let n=Number(t);if(Number.isFinite(n)){let e=new Date(n);return Number.isFinite(e.getTime())?e:void 0}let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}}}function Ghe(e){if(e instanceof Date||!e||typeof e!=`object`)return J$(e);let t=J$(e.createdAt)??J$(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return J$(n.createdAt)??J$(n.created_at)}function Y$(e){if(typeof e==`string`)return[e];if(e?.length)return e}function X$(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}const Z$=/* @__PURE__ */ new WeakMap;function Khe(e){let t=Z$.get(e);if(t)return t;let n=Uhe();return Z$.set(e,n),n}async function Q$(e,t){let n=new URLSearchParams(e),r=n.get(`sig`),i=n.getAll(`sig`),a=Number(n.get(`exp`));n.delete(`sig`);let o=await WW(M$(n).toString(),t);return i.length===1&&!!r&&DU(r,o)&&/* @__PURE__ */ new Date(a*1e3)>=/* @__PURE__ */ new Date}function $$(e,t){if(e.cachedTrustedClients?.has(t))throw new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:`trusted clients must be updated manually`})}async function e1(e,t,n){let r=Khe(t),i=r.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let a=await e.context.adapter.findOne({model:t.schema?.oauthClient?.modelName??`oauthClient`,where:[{field:`clientId`,value:n}]}),o=z$(t);if(a?.clientDiscoveryId){let t=a.clientDiscoveryId,r=o.find(e=>e.id===t);if(!r?.matches(n)||(a=await r.resolve(e,n,a),!a))return null}else if(a)return t.cachedTrustedClients?.has(n)&&r.set(n,Object.assign({},a)),a;else for(let t of o){if(!t.matches(n))continue;let r=await t.resolve(e,n,null);if(r){a=r;break}}return a}function t1(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}const n1=async e=>{let t=await FU(`SHA-256`).digest(new TextEncoder().encode(e));return me.encode(new Uint8Array(t),{padding:!1})};async function r1(e,t,n){if(t===`encrypted`)return await HW({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new D(`Unsupported decryption storageMethod type '${t}'`)}async function qhe(e,t,n,r){let i=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r&&t.prefix?.clientSecret){if(r.startsWith(t.prefix?.clientSecret))r=r.replace(t.prefix.clientSecret,``);else throw new O(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await n1(r):void 0;return!!e&&DU(e,n)}if(typeof i==`object`&&`hash`in i){if(i.verify)return!!r&&await i.verify(r,n);{let e=r?await i.hash(r):void 0;return!!e&&DU(e,n)}}if(i===`encrypted`)try{let t=await r1(e,i,n);return!!r&&DU(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await r1(e,i,n);return!!r&&DU(t,r)}throw new D(`Unsupported verify storageMethod type '${i}'`)}async function i1(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await VW({key:e.context.secretConfig,data:n});if(r===`hashed`)return await n1(n);if(typeof r==`object`&&`hash`in r)return await r.hash(n);if(typeof r==`object`&&`encrypt`in r)return await r.encrypt(n);throw new D(`Unsupported storeClientSecret type '${r}'`)}async function a1(e=`hashed`,t,n){if(e===`hashed`)return await n1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`storeToken: unsupported storageMethod type '${e}'`)}async function o1(e=`hashed`,t,n){if(e===`hashed`)return await n1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`getStoredToken: unsupported storageMethod type '${e}'`)}const s1=/^Basic +/i,Jhe=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Yhe(e){return e.match(Jhe)?.[1]}const c1=[`client_secret`,`client_assertion`,`client_assertion_type`];function l1(e){throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function Xhe(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&l1(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&l1(`${e} must be a string`),r[e]=t)};for(let e of c1)Object.hasOwn(t,e)&&i(e,t[e]);let a=!!e?.headers.get(`authorization`);if(e&&(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`)){let t=new URLSearchParams(await e.clone().text()),r=t.getAll(`client_id`).filter(e=>e.length>0);r.length>1&&l1(`client_id must not be repeated`),n=r[0];for(let e of c1){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&l1(`${e} must not be repeated`),n.length===1&&i(e,n[0])}}let o=r.client_secret!==void 0,s=r.client_assertion!==void 0||r.client_assertion_type!==void 0;(a&&(o||s)||o&&s)&&l1(`A request must use only one client authentication method`),t.client_id=n;for(let e of c1)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function Zhe(e){if(s1.test(e))try{let{clientId:t,clientSecret:n}=rX(e);return{client_id:t,client_secret:n}}catch{throw new O(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function u1(e,t){let n=e.grantTypes&&e.grantTypes.length>0?e.grantTypes:[`authorization_code`];return t===`refresh_token`&&n.includes(`authorization_code`)?!0:n.includes(t)}function d1(e,t){if(!t||!e.scopes)return;let n=new Set(e.scopes);for(let e of t)if(!n.has(e))throw new O(`BAD_REQUEST`,{error_description:`client does not allow scope ${e}`,error:`invalid_scope`})}function f1(e,t){let n=t?.method===`client_secret_basic`,r=t?.scheme??(n?`Basic`:void 0);throw new O(r?`UNAUTHORIZED`:`BAD_REQUEST`,{error_description:e,error:`invalid_client`},r?{"WWW-Authenticate":r}:void 0)}async function p1(e,t,n,r,i,a,o,s){let c=await e1(e,t,n);c||f1(`client not found`,{method:s}),c.disabled&&f1(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&f1(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||U$(t,c.tokenEndpointAuthMethod))&&!a)throw new O(`BAD_REQUEST`,{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:`invalid_client`});if(a||(c.tokenEndpointAuthMethod!==`none`&&!r&&f1(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&f1(`public client, client secret should not be received`,{method:s}),r&&!await qhe(e,t,c.clientSecret,r)&&f1(`invalid client_secret`,{method:s})),d1(c,i),o&&!u1(c,o))throw new O(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function m1(e){if(e)return typeof e==`string`?JSON.parse(e):e}function h1(e){return{clientId:e?.clientId,clientSecret:e?.kind===`client_secret`?e.clientSecret:void 0,preVerified:e?.kind===`pre_verified`,authMethod:e?.method,confirmation:e?.kind===`pre_verified`?e.confirmation:void 0}}async function g1(e,t,n){let r={...e.body??{}};await Xhe(e.request,r);let i=e.request?.headers.get(`authorization`)??void 0;if(r.client_assertion_type||r.client_assertion){if(!r.client_assertion||!r.client_assertion_type)throw new O(`BAD_REQUEST`,{error_description:`client_assertion and client_assertion_type must both be provided`,error:`invalid_client`});let i=r.client_assertion,a=r.client_assertion_type,o=Lhe(t,a);if(o){let s=await o.strategy.authenticate({ctx:e,opts:t,assertion:i,assertionType:a,clientId:r.client_id,expectedAudience:n});return{kind:`pre_verified`,method:o.method,clientId:s.clientId,confirmation:s.confirmation}}let{verifyClientAssertion:s}=await Promise.resolve().then(()=>b_e).then(e=>e.o);return{kind:`pre_verified`,method:`private_key_jwt`,clientId:(await s(e,t,i,a,r.client_id,n)).clientId}}if(i&&!s1.test(i)){let e=Yhe(i);if(!e)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});f1(`unsupported authorization scheme`,{scheme:e})}if(i&&s1.test(i)){let e=Zhe(i);if(e)return{kind:`client_secret`,method:`client_secret_basic`,clientId:e.client_id,clientSecret:e.client_secret}}return r.client_id&&r.client_secret?{kind:`client_secret`,method:`client_secret_post`,clientId:r.client_id,clientSecret:r.client_secret}:r.client_id?{kind:`public`,method:`none`,clientId:r.client_id}:null}function _1(e){let t=e.split(` `).map(e=>e.trim()),n=/* @__PURE__ */ new Set;for(let e of t)(e===`login`||e===`consent`||e===`create`||e===`select_account`||e===`none`)&&n.add(e);return new Set(n)}function Qhe(e){let t=e.redirectUris?.[0];if(!t)throw new D(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function $he(e,t,n){return WW(`${Qhe(t)}.${e}`,n)}async function v1(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?$he(e,t,n.pairwiseSecret):e}async function y1(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function b1(e,t,n,r){let i=[{field:`clientId`,value:t},{field:`userId`,value:n}];if(r)return e.context.adapter.findOne({model:`oauthConsent`,where:[...i,{field:`referenceId`,value:r}]});for(let t=0;;t+=100){let n=await e.context.adapter.findMany({model:`oauthConsent`,where:i,limit:100,offset:t,sortBy:{field:`id`,direction:`asc`}}),r=n.find(e=>!e.referenceId);if(r||n.length<100)return r??null}}function x1(e){let t=Object.create(null);for(let n of new Set(e.keys())){let r=e.getAll(n);t[n]=r.length===1?r[0]:r}return t}function S1(e,t){if(!t)return!1;let n=J$(e);return n?n.getTime()>=t.getTime():!1}function C1(e,t){let n=new URLSearchParams(e),r=n.get(`prompt`)?.split(` `),i=r?.findIndex(e=>e===t)??-1;return i>=0&&(r?.splice(i,1),r?.length?n.set(`prompt`,r.join(` `)):n.delete(`prompt`)),n}function w1(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function T1(e,t){if(e.tokenEndpointAuthMethod===`none`)return`pkce is required for public clients`;let n=t?.scopes??[],r=n.includes(`openid`),i=typeof t?.nonce==`string`&&t.nonce.length>0,a=r&&i;return n.includes(`offline_access`)&&!a?`pkce or OIDC nonce is required when requesting offline_access scope`:e.requirePKCE??!0?`pkce is required for this client`:!1}const ege=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,tge=/* @__PURE__ */ new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function E1(e){let t=e.protocol.slice(0,-1),n=e.href.slice(e.protocol.length);return e.protocol!==`http:`&&e.protocol!==`https:`&&e.host.length===0&&n.startsWith(`/`)&&!n.startsWith(`//`)&&ege.test(t)}function nge(e){return tge.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function D1(e){return E1(e)||nge(e)}const O1=nee().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),Ke}wq.includes(n.protocol)?t.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`}):(e.includes(`#`)&&t.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),n.protocol===`http:`&&!SY(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))}),rge=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function k1(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))rge.has(r)?t.push(r):n[r]=i;return t.length>0&&C.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}const A1=ze(k(),rt()).nullable(),ige=We({essential:Je().optional(),value:k().optional(),values:Be(k()).optional()}).nullable(),age=A({acr:ige.optional()}).catchall(A1),oge=We({userinfo:ze(k(),A1).optional(),id_token:age.optional()});function sge(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function j1(e){let t=sge(e),n=oge.safeParse(t);return n.success?n.data:void 0}const M1=Ae([k(),ze(k(),rt())]),cge=M1,N1=M1.refine(e=>j1(e)!==void 0,{error:`claims must be a valid Claims request object`});function lge(e){return e===void 0||j1(e)!==void 0}function P1(e,t){let n=j1(e)?.userinfo;if(!n)return[];let r=Object.keys(n);if(!t)return r;let i=new Set(t);return r.filter(e=>i.has(e))}function uge(e,t){let n=j1(e);if(!n)return e===void 0;let r=n.id_token?.acr;if(!r||r.essential!==!0)return!0;let i=r.value===void 0||r.value===t,a=r.values===void 0||r.values.includes(t);return i&&a}function dge(e,t){let n=j1(e);if(!n)return;let r=new Set(t),i=Object.fromEntries(Object.entries(n.userinfo??{}).filter(([e])=>r.has(e))),a=Object.keys(i).length?{...n,userinfo:i}:Object.fromEntries(Object.entries(n).filter(([e])=>e!==`userinfo`));return Object.keys(a).length?a:void 0}function F1(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}const I1={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>F1(e.name).given},family_name:{scope:`profile`,resolve:e=>F1(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},L1=Object.keys(I1);function R1(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}const fge=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function pge(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))fge.has(r)?t.push(r):n[r]=i;return t.length>0&&C.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function z1(e){let{ctx:t,opts:n,user:r,client:i,scopes:a,resources:o,referenceId:s,metadata:c,grantType:l,sessionId:u,perRequestClaims:d,resourcePolicyClaims:f}=e,p=await Rhe(n,{ctx:t,opts:n,user:r,client:i,scopes:a,grantType:l,referenceId:s,sessionId:u,resources:o,metadata:c}),m=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:r,scopes:a,resources:o,referenceId:s,metadata:c}):{};return pge({...p,...d??{},...m,...f})}const mge=[`javascript:`,`data:`,`vbscript:`],B1=k().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),Ke;e.includes(`#`)?t.addIssue({code:`custom`,message:`resource must not contain a fragment`}):mge.includes(new URL(e).protocol)&&t.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),hge=Ze([`none`,`consent`,`login`,`create`,`select_account`]),gge=k().superRefine((e,t)=>{let n=e.split(` `).map(e=>e.trim()).filter(Boolean),r=/* @__PURE__ */ new Set;if(!n.length)t.addIssue({code:`custom`,message:`prompt must include at least one value`});else{for(let e of n){let n=hge.safeParse(e);n.success?r.add(n.data):t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`})}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}}),V1=A({keys:Be(ze(k(),rt())).min(1)}),_ge=Ae([Le(),k().trim().min(1)]).transform((e,t)=>{let n=typeof e==`number`?e:Number(e);return!Number.isInteger(n)||n<0?(t.addIssue({code:`custom`,message:`max_age must be a non-negative integer`}),Ke):n}),vge=k().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),H1=A({response_type:k().pipe(Ze([`code`])).optional(),request:k().optional(),request_uri:k().optional(),redirect_uri:O1.optional(),scope:k().optional(),state:k().optional(),client_id:k().min(1,`client_id is required`),prompt:gge.optional(),display:k().optional(),ui_locales:k().optional(),max_age:_ge.optional(),acr_values:k().optional(),login_hint:k().optional(),id_token_hint:k().optional(),code_challenge:k().optional(),code_challenge_method:k().pipe(Ze([`S256`])).optional(),nonce:k().optional(),claims:cge.optional(),dpop_jkt:vge.optional(),resource:Ae([B1,Be(B1).min(1)]).optional()}).passthrough(),yge=H1.extend({redirect_uri:O1.optional(),claims:N1.optional()}),bge=A({type:Ye(`authorization_code`),query:yge,sessionId:k(),userId:k(),referenceId:k().optional(),authTime:Le().optional(),resource:Be(k()).optional()}).passthrough(),U1=A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),token_endpoint_auth_method:k().trim().min(1).optional(),jwks:V1.optional(),jwks_uri:k().optional(),grant_types:Be(k().trim().min(1)).min(1).optional(),response_types:Be(Ze([`code`])).optional(),application_type:Ze([`web`,`native`]).optional(),subject_type:Ze([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:Je().optional(),resources:Be(B1).optional(),skip_consent:Ue({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),xge=U1.omit({skip_consent:!0}).extend({client_id:k().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:k().optional(),client_secret_expires_at:Le().int().nonnegative().optional(),client_id_issued_at:Le().int().nonnegative().optional()}).loose(),W1=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],Sge=new Set(W1);async function G1(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=B1.safeParse(t);return r.success?{ok:!0}:{ok:!1,reason:`resource identifier ${t} is invalid: ${r.error.issues[0]?.message??`not an absolute URI`}`}}async function Cge(e,t){let n=await G1(e,t);if(!n.ok)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}const wge=e=>`${e}/oauth2/userinfo`;async function Tge(e){if(!(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`))return;let t;try{t=await e.clone().text()}catch{return}if(!t)return;let n=new URLSearchParams(t).getAll(`resource`).filter(e=>e.length>0);return n.length>0?n:void 0}function Ege(e){if(e!=null){if(typeof e==`string`)return[e];if(Array.isArray(e)){let t=e.filter(e=>typeof e==`string`&&e.length>0);return t.length>0?t:void 0}}}async function K1(e,t,n,r=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>64)return!1;let a=new Set(r),o=/* @__PURE__ */ new Set;for(let e of i)a.has(e)||o.add(e);return o.size===0||(await Promise.all(Array.from(o,n=>Z1(e,t,n)))).every(Boolean)}async function q1(e,t,n){let r=Ege(n.resource),i=n.requestedScopes.includes(`openid`),a=wge(e.context.baseURL??``);if(!r)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let o=[...new Set(r)],s=[];for(let n of o){if(n===a)continue;let r=await Z1(e,t,n);if(r){if(r.disabled)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r)}else throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:c}=J1(t);c&&s.length>0&&await Dge(e,t,n.clientId,s);let l=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=l.filter(e=>t.has(e));if(n.length===0)throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});l=n}let u=null,d=null;for(let e of s)e.accessTokenTtl!=null&&(u=u===null?e.accessTokenTtl:Math.min(u,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(d=d===null?e.refreshTokenTtl:Math.min(d,e.refreshTokenTtl));let f=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set;for(let e of s)e.signingAlgorithm&&f.add(e.signingAlgorithm),e.signingKeyId&&p.add(e.signingKeyId);if(f.size>1)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(p.size>1)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let m=f.values().next().value??null,h=p.values().next().value??null,g={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(g,e.customClaims);let _=s.some(e=>e.dpopBoundAccessTokensRequired===!0),v=i?[...o,a]:o,y=[...new Set(v)];return{audienceClaim:y.length===1?y[0]:y,accessTokenTtl:u,refreshTokenTtl:d,signingAlgorithm:m,signingKeyId:h,rawCustomClaims:g,dpopBoundAccessTokensRequired:_,effectiveScopes:l}}async function Dge(e,t,n,r){if(r.length===0)return;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,a=await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n}]}),o=new Set(a?.map(e=>e.resourceId)??[]),s=r.filter(e=>!o.has(e.identifier));if(s.length>0)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function Oge(e,t,n,r){if(r.length===0)return!1;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`;return((await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n},{field:`resourceId`,operator:`in`,value:r}],limit:1}))?.length??0)>0}async function kge(e,t,n){if(n.length===0)return{};let r=await e.context.adapter.findMany({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,operator:`in`,value:n}]}),i=new Map(r.map(e=>[e.identifier,e])),a={};for(let e of n){let t=i.get(e);t?.customClaims&&typeof t.customClaims==`object`&&Object.assign(a,t.customClaims)}return a}function J1(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}const Y1=/* @__PURE__ */ new Map;function X1(e){e===void 0?Y1.clear():Y1.delete(e)}async function Z1(e,t,n){if(await e0(e.context,t),t.cachedResources?.has(n)){let e=Y1.get(n);if(e)return Object.assign({},e)}let r=await e.context.adapter.findOne({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,value:n}]});return r&&t.cachedResources?.has(n)&&Y1.set(n,Object.assign({},r)),r}function Age(e){return e.name??e.identifier}function jge(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function Q1(e,t){return{identifier:e.identifier,name:Age(e),accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}function Mge(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=Q1(e,n);return i}let r={updatedAt:n};return e.name!==void 0&&(r.name=e.name),e.accessTokenTtl!==void 0&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl!==void 0&&(r.refreshTokenTtl=e.refreshTokenTtl),e.signingAlgorithm!==void 0&&(r.signingAlgorithm=e.signingAlgorithm),e.signingKeyId!==void 0&&(r.signingKeyId=e.signingKeyId),e.allowedScopes!==void 0&&(r.allowedScopes=e.allowedScopes),e.customClaims!==void 0&&(r.customClaims=e.customClaims),e.dpopBoundAccessTokensRequired!==void 0&&(r.dpopBoundAccessTokensRequired=e.dpopBoundAccessTokensRequired),e.disabled!==void 0&&(r.disabled=e.disabled),e.metadata!==void 0&&(r.metadata=e.metadata),r}const Nge=/no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;function Pge(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=Nge.test(r instanceof Error?r.message:String(r)),r=r instanceof Error?r.cause:void 0;n?e.logger.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`):e.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",t)}let $1=/* @__PURE__ */ new WeakMap;function Fge(e,t){let n=e.adapter,r=$1.get(n);r||(r=/* @__PURE__ */ new WeakMap,$1.set(n,r));let i=r.get(t);if(i)return i;let a={completed:!1,promise:null};return r.set(t,a),a}async function Ige(e,t){let n=jge(t);if(n.length===0)return;let r=t.resourceSeedMode??`insertOnly`,i=t.schema?.oauthResource?.modelName??`oauthResource`;for(let a of n){let n=await G1(t,a.identifier);if(!n.ok){C.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!Sge.has(o.signingAlgorithm)){C.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${W1.join(`, `)}. Continuing without an algorithm override.`);let{signingAlgorithm:e,...t}=o;o=t}let s=[{field:`identifier`,value:o.identifier}],c=await e.adapter.findOne({model:i,where:s}),l=/* @__PURE__ */ new Date;if(!c)try{await e.adapter.create({model:i,data:Q1(o,l)});continue}catch(t){if(!await e.adapter.findOne({model:i,where:s}).catch(()=>null))throw t}r!==`insertOnly`&&await e.adapter.update({model:i,where:s,update:Mge(o,r,l)})}}async function e0(e,t){let n=Fge(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=Ige(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Lge(e){let t=J1(e);C.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function t0(e){return e.headers?.get(`dpop`)??void 0}function n0(e,t){let{baseURL:n}=e.context,r=n.length;for(;r>0&&n[r-1]===`/`;)r--;let i=n.slice(0,r);if(!e.request||!i)return`${i}${t}`;let a=new URL(i).pathname.replace(/\/$/,``),o=new URL(e.request.url).pathname;return`${i}${o.startsWith(`${a}/`)?o.slice(a.length):t}`}const Rge=/* @__PURE__ */ new Set([`openid`,`profile`,`email`,`offline_access`]);function r0(e){return Rge.has(e)}function i0(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function a0(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`public clients cannot be assigned client_credentials scopes`});let i=new Set(r.scopes??[]),a=e.filter(e=>!i.has(e)||r0(e));if(a.length>0)throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}function zge(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(I1))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function o0(e,t){let n={};for(let[r,i]of Object.entries(e??{}))i!==void 0&&(t&&r in t||(n[r]=i));return n}function Bge(e){let t=e.headers?.get(`authorization`),n=aZ(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new E(`BAD_REQUEST`,{error_description:`Multiple access token transport methods are not allowed`,error:`invalid_request`});let i=n??(r?{scheme:`Bearer`,token:r}:void 0);return{authorization:i,token:i?.token}}async function Vge(e,t){let{authorization:n}=Bge(e);if(!n?.token)throw new E(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await O0(e,t,n.token);if(dZ(r)&&!e.request)throw new E(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await xZ({payload:r,authorization:n,proofJwt:t0(e),method:e.request?.method??`GET`,url:n0(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:nZ(e.context.internalAdapter)})}catch(e){throw bZ(e)?new E(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new E(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=zge(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||Vhe(t))?await e1(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await v1(o.id,l,t));let u=a?.length?await Bhe(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:l??void 0,requestedClaims:i}):{},d=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...o0(u,s),...o0(d),sub:s.sub}}const Hge=Object.fromEntries(L1.map(e=>[e,void 0]));function s0(e){return uZ(e)?`DPoP`:`Bearer`}async function Uge(e,t){let n=e.body.grant_type;if(!B$(t).includes(n))throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return u_e(e,t);case`client_credentials`:return d_e(e,t);case`refresh_token`:return f_e(e,t);default:{let r=Ihe(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:Wge(e,t,n)});throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function Wge(e,t,n){return{getClient:n=>e1(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=h1(await g1(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new E(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await p1(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:c}},issueTokens:r=>{if(!n)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return b0(e,t,{...r,grantType:n})},hashToken:(e,n)=>a1(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>x0);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>x0);return i(e,t,n,r)}}}async function Gge(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=K$(e.context).options,u=n?.id??r.clientId;return w$(e,{options:l,header:{typ:`at+jwt`},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:X$(i),client_id:r.clientId,azp:r.clientId,scope:a.join(` `),sid:o?.sid,iss:l?.jwt?.issuer??e.context.baseURL,iat:s,exp:c,jti:ZH(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function Kge(e,t){let n;n=t===`EdDSA`?`SHA-512`:t.endsWith(`384`)?`SHA-384`:t.endsWith(`512`)?`SHA-512`:`SHA-256`;let r=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(e)));return mP(r.slice(0,r.length/2))}async function qge(e,t,n,r,i,a,o,s,c,l){let u=Math.floor(Date.now()/1e3),d=u+(t.idTokenExpiresIn??36e3),f=await v1(n.id,r,t),p=s==null?void 0:Math.floor(s.getTime()/1e3),m=k1(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:m1(r.metadata)}):void 0),h=t.disableJwtPlugin?void 0:K$(e.context).options,g=!t.disableJwtPlugin&&!h?.jwt?.sign?await C$(e,h):void 0,_=t.disableJwtPlugin?`HS256`:g?.alg??h?.jwks?.keyPairConfig?.alg,v=c?await Kge(c,_):void 0,y=!!(r.enableEndSession||r.backchannelLogoutUri),b={...Hge,auth_time:p,acr:`0`,...m,at_hash:v,iss:h?.jwt?.issuer??e.context.baseURL,sub:f,aud:r.clientId,nonce:a,iat:u,exp:d,sid:y?o:void 0},x=k1(l);if(Object.assign(b,o0(x,b)),t.disableJwtPlugin&&!r.clientSecret)return;let S=t.disableJwtPlugin?await new tI(b).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await r1(e,t.storeClientSecret,r.clientSecret))):await w$(e,{options:h,payload:b,resolvedKey:g??void 0});if(S&&v&&h?.jwt?.sign){let e=pI(S);if(e.alg!==_)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`ID token signed with "${e.alg}" but at_hash was computed for "${_}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:`server_error`})}return S}async function c0(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function l0(e,t){if(e.prefix?.refreshToken){if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,``);else throw new E(`BAD_REQUEST`,{error_description:`refresh token not found`,error:`invalid_token`})}return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function Jge(e,t,n,r,i,a,o,s,c,l,u,d){let f=a.iat??Math.floor(Date.now()/1e3),p=a?.exp??f+(t.accessTokenExpiresIn??3600),m=t.generateOpaqueAccessToken?await t.generateOpaqueAccessToken():ZH(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await a1(t.storeTokens,m,`access_token`),clientId:r.clientId,sessionId:a?.sid,userId:n?.id,referenceId:s,authorizationCodeId:c,resources:o,refreshId:l,confirmation:u,requestedUserInfoClaims:d?.length?d:void 0,scopes:i,createdAt:/* @__PURE__ */ new Date(f*1e3),expiresAt:/* @__PURE__ */ new Date(p*1e3)}}),(t.prefix?.opaqueAccessToken??``)+m}async function u0(e,t,n){let r=await e.context.adapter.findMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]});r.length&&await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,operator:`in`,value:r.map(e=>e.id)}]}),await e.context.adapter.deleteMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]})}async function Yge(e,t){let n=async n=>{try{await e.context.adapter.deleteMany({model:n,where:[{field:`authorizationCodeId`,value:t}]})}catch(t){e.context.logger.error(`authorization code replay cleanup failed`,t)}};await n(`oauthAccessToken`),await n(`oauthRefreshToken`)}async function d0(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=s.iat??Math.floor(Date.now()/1e3),m=s?.exp??p+(t.refreshTokenExpiresIn??2592e3),h=t.generateRefreshToken?await t.generateRefreshToken():ZH(32,`A-Z`,`a-z`),g=s?.sid,_={token:await a1(t.storeTokens,h,`refresh_token`),clientId:a.clientId,sessionId:g,userId:n.id,referenceId:r,authorizationCodeId:i,authTime:l,confirmation:d,requestedUserInfoClaims:f?.length?f:void 0,scopes:o,resources:u,createdAt:/* @__PURE__ */ new Date(p*1e3),expiresAt:/* @__PURE__ */ new Date(m*1e3)};if(!c?.id)return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:_})).id,token:await c0(t,h,g)};let v=/* @__PURE__ */ new Date(p*1e3),y={revoked:v,rotatedAt:v},b=t.refreshTokenReuseInterval??0;if(b>0&&(y.rotationReplayExpiresAt=/* @__PURE__ */ new Date((p+b)*1e3)),!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:c.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:y}))throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:_})).id,token:await c0(t,h,g)}}async function f0(e,t,n){let r=await q1(e,t,{resource:n.resources,clientId:n.clientId,requestedScopes:n.requestedScopes}),i=r.accessTokenTtl===null?n.scopeExpiresAtSeconds:n.iat+r.accessTokenTtl,a=t.refreshTokenExpiresIn??2592e3,o=r.refreshTokenTtl===null?a:Math.min(r.refreshTokenTtl,a);return{audienceClaim:r.audienceClaim,effectiveScopes:r.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(n.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:n.iat+o,refreshResources:n.refreshToken?.resources??n.originalResources??n.resources,signingAlgorithm:r.signingAlgorithm,signingKeyId:r.signingKeyId,resourceCustomClaims:r.rawCustomClaims,dpopBoundAccessTokensRequired:r.dpopBoundAccessTokensRequired}}function p0(e){throw new E(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Xge(e){let t=m1(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function m0(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=uZ(n.refreshToken?.confirmation),a=i??r,o=t0(e),s=Xge(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&p0(`DPoP proof header is required`);else try{return{jkt:(await vZ({proofJwt:o,method:`POST`,url:n0(e,e.path??`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:nZ(e.context.internalAdapter)})).jkt}}catch(e){throw iZ(e)&&p0(e.message),e}}function h0(e){return e?[...new Set(e)].sort():void 0}function g0(e,t){let n=h0(e),r=h0(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function _0(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Zge(e,t){return _0(e)===_0(t)}function Qge(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.jkt==`string`&&t[`x5t#S256`]===void 0||typeof t[`x5t#S256`]==`string`&&t.jkt===void 0}function $ge(e){return e===`Bearer`||e===`DPoP`}function e_e(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.access_token==`string`&&typeof t.expires_in==`number`&&typeof t.expires_at==`number`&&$ge(t.token_type)&&typeof t.scope==`string`&&(t.refresh_token===void 0||typeof t.refresh_token==`string`)&&(t.id_token===void 0||typeof t.id_token==`string`)}function t_e(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every(e=>typeof e==`string`)&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every(e=>typeof e==`string`))&&(n.confirmation===void 0||Qge(n.confirmation))&&e_e(t.response)}function v0(e){let t=h0(e.requestedResources);return{effectiveScopes:h0(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function n_e(e,t){return g0(e.effectiveScopes,t.effectiveScopes)&&g0(e.requestedResources,t.requestedResources)&&Zge(e.confirmation,t.confirmation)}async function r_e(e,t){return VW({key:e.context.secretConfig,data:JSON.stringify(t)})}async function i_e(e,t){let n=await HW({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(t_e(r))return r}function y0(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=/* @__PURE__ */ new Date}async function a_e(e,t,n,r,i){(t.refreshTokenReuseInterval??0)<=0||await e.context.adapter.update({model:`oauthRefreshToken`,where:[{field:`id`,value:n.id}],update:{rotationReplayResponse:await r_e(e,{request:r,response:i})}})}async function o_e(e,t,n){if(y0(t)&&t.rotationReplayResponse)try{let r=await i_e(e,t.rotationReplayResponse);return!r||!n_e(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function s_e(e,t,n){let r=Math.floor(Date.now()/1e3),i=await f0(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await m0(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return v0({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function c_e(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function b0(e,t,n){let{client:r,scopes:i,user:a,grantType:o,referenceId:s,sessionId:c,nonce:l,refreshToken:u,authTime:d,verificationValue:f}=n,p=Math.floor(Date.now()/1e3),m=p+(a?t.accessTokenExpiresIn??3600:t.m2mAccessTokenExpiresIn??3600),h=t.scopeExpirations?i.map(e=>t.scopeExpirations?.[e]?x$(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await f0(e,t,{clientId:r.clientId,requestedScopes:i,resources:n.resources,originalResources:n.originalResources,refreshToken:n.refreshToken,iat:p,scopeExpiresAtSeconds:h}),_=g.audienceClaim,v=g.effectiveScopes,y=g.accessTokenExpiresAtSeconds,b=g.refreshTokenExpiresAtSeconds,x=a&&u1(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,ee=a&&v.includes(`openid`),C=m1(r.metadata),te=ee&&a?{...await zhe(t,{ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:C}),...n.idTokenClaims??{}}:void 0,w=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:C,verificationValue:f}):void 0,ne=g.refreshResources,T=n.confirmation??await m0(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),re=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],ie=x&&a&&!S?await d0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,ne,T,re):void 0,ae=S?await z1({ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:C,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:g.resourceCustomClaims}):void 0,[oe,se]=await Promise.all([S?Gge(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:ae,confirmation:T}):Jge(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,ie?.id,T,re),ie||(x&&a?d0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,ne,T,re):void 0)]),ce=ee?await qge(e,t,a,r,v,l,c,d,oe,te):void 0,le={...w,...n.tokenResponse??{},access_token:oe,expires_in:y-p,expires_at:y,token_type:s0(T),refresh_token:se?.token,scope:v.join(` `),id_token:ce};if(u?.id&&se?.id)try{await a_e(e,t,u,v0({effectiveScopes:v,requestedResources:n.resources,confirmation:T}),le)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(le)}async function l_e(e,t,n,r,i,a){let o=await a1(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await Yge(e,o),new E(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let c;try{c=JSON.parse(s.value)}catch{throw new E(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let l=bge.safeParse(c);if(!l.success)throw new E(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let u=l.data;if(u.query.client_id!==r)throw new E(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let d=u.query.redirect_uri;if(d){if(!i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(d!==i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let f=Y$(u.resource)??Y$(u.query.resource),p=a??f;if(a&&f){let e=new Set(a),t=new Set(f);for(let n of e)if(!t.has(n))throw new E(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:u,effectiveResources:p,authorizedResources:f,authorizationCodeId:o}}async function u_e(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=Y$(l);if(!n)throw new E(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new E(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let d=n&&r,f=n&&o&&s;if(!d&&!f&&!i)throw new E(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let p=await p1(e,t,n,r,void 0,i,`authorization_code`,a),{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await l_e(e,t,o,n,c,u),v=m.query.scope?.split(` `);if(!v)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});if(d1(p,v),T1(p,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!f)throw new E(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(f||d||i))throw new E(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let y=!!m.query?.code_challenge,b=!!s;if(y||b){if(y&&!b)throw new E(`BAD_REQUEST`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!y&&b)throw new E(`BAD_REQUEST`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((m.query?.code_challenge_method===`S256`?await JY(s):void 0)!==m.query?.code_challenge)throw new E(`BAD_REQUEST`,{error_description:`code verification failed`,error:`invalid_grant`})}if(!m.userId)throw new E(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let x=await e.context.internalAdapter.findUserById(m.userId);if(!x)throw new E(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:m.sessionId}]});if(!S||S.expiresAt</* @__PURE__ */ new Date)throw new E(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let ee=m.authTime==null?Ghe(S):J$(m.authTime),C=P1(m.query.claims,R1(t));return b0(e,t,{client:p,scopes:m.query.scope?.split(` `)??[],user:x,grantType:`authorization_code`,referenceId:m.referenceId,sessionId:S.id,nonce:m.query?.nonce,authTime:ee,verificationValue:m,authorizationCodeId:_,requestedUserInfoClaims:C,resources:h,originalResources:g})}async function d_e(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=Y$(s);if(!n)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await p1(e,t,n,r,void 0,i,`client_credentials`,a);if(l.tokenEndpointAuthMethod===`none`)throw new E(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let u=l.clientCredentialsScopes;if(!u?.length)throw new E(`BAD_REQUEST`,{error_description:`client has no authorized client_credentials scopes`,error:`unauthorized_client`});let d=o?.split(` `);if(d){let e=new Set(u),t=d.filter(t=>!e.has(t)||r0(t));if(t.length)throw new E(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],b0(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function f_e(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=Y$(c);if(!n)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new E(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let u=await p1(e,t,n,r,void 0,i,`refresh_token`,a),d=await l0(t,o),f=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await o1(t.storeTokens,d.token,`refresh_token`)}]});if(!f)throw new E(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(f.clientId!==n||f.expiresAt</* @__PURE__ */ new Date)throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(l&&f.resources&&!l.every(e=>f.resources?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`requested resource invalid`,error:`invalid_target`});let p=f?.scopes,m=s?.split(` `);if(m){let e=new Set(p);for(let t of m)if(!e.has(t))throw new E(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}if(d1(u,m??p),f.revoked){if(y0(f)){let n=await o_e(e,f,await s_e(e,t,{client:u,refreshToken:f,scopes:m??p,resources:l??f.resources}));if(n)return c_e(e,n);throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await u0(e,n,f.userId),new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let h=await e.context.internalAdapter.findUserById(f.userId);if(!h)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let g=f.authTime==null?void 0:J$(f.authTime);return b0(e,t,{client:u,scopes:m??p,user:h,grantType:`refresh_token`,referenceId:f.referenceId,authorizationCodeId:f.authorizationCodeId,sessionId:f.sessionId,refreshToken:f,resources:l??f.resources,authTime:g,requestedUserInfoClaims:f.requestedUserInfoClaims})}var x0=/* @__PURE__ */ O$({introspectEndpoint:()=>A0,requireActiveAccessToken:()=>y_e,requireActiveAccessTokenWithClaims:()=>O0,validateAccessToken:()=>D0});const S0=`Invalid access token`,p_e=`Bearer error="invalid_token", error_description="${S0}"`;function C0(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function m_e(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function w0(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&Oge(e,t,r,a)}async function h_e(e,t,n,r){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let i=K$(e.context),a=i.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await $F(n,cI(await FZ(n,{jwksFetch:a?.jwks?.remoteUrl?a.jwks.remoteUrl:async()=>(await i.endpoints.getJwks(e))?.response,jwksCacheKey:i})),{issuer:s})).payload}catch(e){if(e instanceof eP||e instanceof oP)return{active:!1};throw e instanceof TypeError||q$(e)?new O(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`}):e}let l=c.aud;if(!await K1(e,t,l,[o])||!c.azp)return{active:!1};let u=await e1(e,t,c.azp);if(!u||u?.disabled||!await w0(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:m_e(l,o)}))return{active:!1};let d=c.sid;if(d){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:d}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=s0(c.cnf),c}async function g_e(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await o1(t.storeTokens,i,`access_token`)}]});if(!a)throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_token`});if(!a.expiresAt||a.expiresAt</* @__PURE__ */ new Date||a.revoked)return C0();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await e1(e,t,a.clientId),!s||s?.disabled||!await w0(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return C0();let c=a.sessionId??void 0;if(c){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:c}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return C0()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await K1(e,t,o,[u]))return C0();let d=o?[...o]:void 0;d?.length&&a.scopes?.includes(`openid`)&&(d.includes(u)||d.push(u));let f=o?.length?await kge(e,t,o):{},p=s?await z1({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:m1(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:f}):{},m=(t.disableJwtPlugin?void 0:K$(e.context))?.options;return{payload:{...p,active:!0,iss:m?.jwt?.issuer??e.context.baseURL,aud:X$(d),client_id:a.clientId,azp:a.clientId,sub:l?.id,sid:c,exp:Math.floor(new Date(a.expiresAt).getTime()/1e3),iat:Math.floor(new Date(a.createdAt).getTime()/1e3),scope:a.scopes?.join(` `),token_type:s0(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function __e(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await o1(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_token`});if(!i.clientId||i.clientId!==r||!i.expiresAt||i.expiresAt</* @__PURE__ */ new Date||i.revoked)return{active:!1};let a=i.sessionId??void 0;if(a){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:a}]});(!t||t.expiresAt</* @__PURE__ */ new Date)&&(a=void 0)}let o;return i.userId&&(o=await e.context.internalAdapter.findUserById(i?.userId)??void 0),{active:!0,client_id:r,iss:((t.disableJwtPlugin?void 0:K$(e.context))?.options)?.jwt?.issuer??e.context.baseURL,sub:o?.id,sid:a,exp:Math.floor(new Date(i.expiresAt).getTime()/1e3),iat:Math.floor(new Date(i.createdAt).getTime()/1e3),scope:i.scopes?.join(` `),token_type:s0(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function T0(){return new O(`UNAUTHORIZED`,{error_description:S0,error:`invalid_token`},{"WWW-Authenticate":p_e})}function v_e(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function E0(e,t,n,r){try{return{payload:await h_e(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(e)}try{return await g_e(e,t,n,r)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw T0()}async function D0(e,t,n,r){return(await E0(e,t,n,r)).payload}async function y_e(e,t,n,r){let i=await D0(e,t,n,r);if(i.active)return i;throw T0()}async function O0(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await E0(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw T0()}async function k0(e,t,n,r){if(!n.active||!n.sub)return n;let i=n.client_id??n.azp;if(!i)return n;let a=i===r.clientId?r:await e1(e,t,i);if(!a)return n;let o=await v1(n.sub,a,t);return{...n,sub:o}}async function A0(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new O(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=oZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await p1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return k0(e,t,await D0(e,t,n,c.clientId),c)}catch(e){if(e instanceof O){if(r===`access_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return k0(e,t,await __e(e,t,(await l0(t,n)).token,c.clientId),c)}catch(e){if(e instanceof O){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof O){if(v_e(e))return{active:!1};throw e}throw e instanceof Error?(C.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(C.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}function j0(e){return e?.get(`sec-fetch-mode`)===`cors`}var b_e=/* @__PURE__ */ e({a:()=>z2,c:()=>u2,d:()=>e2,f:()=>Q0,h:()=>$0,i:()=>a4,l:()=>c2,n:()=>$2,o:()=>$_e,r:()=>n4,s:()=>C2,t:()=>d4,u:()=>X0});async function x_e(e,t,n){let r=await t4.get(),i=r?.query;if(!i)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `)??[],s=R1(t),c=P1(a.get(`claims`),s),l=a.get(`client_id`);if(!l)throw new E(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_client`});let u=e.body.scope?.split(` `);if(u&&!u.every(e=>o?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let d=e.body.claims,f=d===void 0?c:P1(d,s);if(d!==void 0&&!f.every(e=>c.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});if(e.body.accept!==!0)return{redirect:!0,url:o4(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,d4(e,t))};let p=await HJ(e),m=_1(a.get(`prompt`)??``).has(`login`),h=m&&S1(p?.session.createdAt,r?.signedQueryIssuedAt);if(m&&!h)return e?.headers?.set(`accept`,`application/json`),e.query=x1(a),await n(e);let g=await y1(t,{user:p?.user,session:p?.session,scopes:u??o}),_=await b1(e,l,p?.user.id,g),v=Math.floor(Date.now()/1e3),y=a.getAll(`resource`),b={clientId:l,userId:p?.user.id,scopes:u??o,requestedUserInfoClaims:f,createdAt:/* @__PURE__ */ new Date(v*1e3),updatedAt:/* @__PURE__ */ new Date(v*1e3),resources:y.length?y:void 0,referenceId:g};if(_?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:_.id}],update:{resources:b.resources,scopes:b.scopes,requestedUserInfoClaims:b.requestedUserInfoClaims,updatedAt:/* @__PURE__ */ new Date(v*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...b,scopes:b.scopes}}),u&&a.set(`scope`,b.scopes.join(` `)),d!==void 0){let e=dge(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let x=C1(a,`consent`);return h&&(x=C1(x,`login`),x=w1(x)),e.query=x1(x),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id})}async function S_e(e,t){if(e.body.selected===!0)return await C_e(e,t);if(e.body.created===!0)return await w_e(e,t);if(e.body.postLogin===!0)return await T_e(e,t);throw new E(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function C_e(e,t){let n=(await t4.get())?.query;if(!n)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=x1(C1(new URLSearchParams(n),`select_account`)),await t(e)}async function w_e(e,t){let n=(await t4.get())?.query;if(!n)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=x1(C1(r,`create`)),await t(e)}async function T_e(e,t){let n=await t4.get(),r=n?.query;if(!r)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=x1(i);let a=await HJ(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id,isPostLoginContinuation:!0})}async function E_e(e,t,n,r){return w$(e,{options:t,payload:{...r,events:{"http://schemas.openid.net/event/backchannel-logout":{}}},header:{typ:`logout+jwt`},resolvedKey:n??void 0})}async function D_e(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await TH(e.context.adapter),o=[{field:`sessionId`,value:r}],[s,c]=await Promise.all([n.findMany({model:`oauthAccessToken`,where:o}),n.findMany({model:`oauthRefreshToken`,where:o})]),l=/* @__PURE__ */ new Set;for(let e of s)l.add(e.clientId);for(let e of c)l.add(e.clientId);if(l.size===0)return null;let u=await n.findMany({model:`oauthClient`,where:[{field:`clientId`,operator:`in`,value:Array.from(l)}]}),d=s.filter(e=>!e.revoked).map(e=>e.id),f=c.filter(e=>!e.revoked&&!e.scopes?.includes(`offline_access`)).map(e=>e.id),p=t.disableJwtPlugin?[]:u.filter(e=>!!e.backchannelLogoutUri&&!e.disabled);return{accessTokenIds:d,refreshTokenIds:f,sessionId:r,targets:(await Promise.all(p.map(async e=>{try{return{client:e,sub:await v1(i,e,t)}}catch(t){return a.warn(`back-channel logout: unable to resolve subject for client ${e.clientId}`,t),null}}))).filter(e=>e!==null)}}catch(e){return a.error(`back-channel logout planning failed`,e),null}}async function O_e(e,t){let n=/* @__PURE__ */ new Date,r=await TH(e.context.adapter),i=await Promise.allSettled([t.accessTokenIds.length>0?r.updateMany({model:`oauthAccessToken`,where:[{field:`id`,operator:`in`,value:t.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),t.refreshTokenIds.length>0?r.updateMany({model:`oauthRefreshToken`,where:[{field:`id`,operator:`in`,value:t.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let t of i)t.status===`rejected`&&e.context.logger.error(`back-channel logout: token revocation update failed`,t.reason);t.targets.length>0&&await k_e(e,t)}async function k_e(e,t){let n=e.context.logger,r=K$(e.context)?.options,i=r?.jwt?.issuer??e.context.baseURL,a=Math.floor(Date.now()/1e3),o=a+120,s=r?.jwt?.sign?null:await C$(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=ZH(32,`a-z`,`A-Z`,`0-9`),d=await E_e(e,r,s,{iss:i,aud:c.clientId,sub:l,sid:t.sessionId,iat:a,exp:o,jti:u}),f=await fetch(c.backchannelLogoutUri,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:new URLSearchParams({logout_token:d}),signal:AbortSignal.timeout(5e3),redirect:`error`});f.status!==200&&f.status!==204&&n.warn(`back-channel logout to client ${c.clientId} returned ${f.status}`)}catch(e){n.warn(`back-channel logout to client ${c.clientId} failed`,e)}}))}function M0(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function N0(e){let t=e.request?.headers??e.headers;if(!t||j0(t))return!1;let n=t.get(`accept`)??``;return t.get(`sec-fetch-mode`)===`navigate`||n.includes(`text/html`)||n.includes(`application/xhtml+xml`)}function P0(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${M0(e)}</title></head><body>${t}</body></html>`,{status:n,headers:{"cache-control":`no-store`,"content-security-policy":`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,pragma:`no-cache`,"x-content-type-options":`nosniff`}})}function F0(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function A_e(e){try{return new URL(F0(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function I0(e){return P0(`Confirm logout`,`<main><h1>Confirm logout</h1><p>Do you want to log out of this account?</p><form method="post" data-oidc-logout-confirmation action="${M0(F0(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function L0(e){return P0(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${M0(e)}`:`Logged out.`}</p></main>`)}function j_e(e,t){return P0(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${M0(e)}</p></main>`,t)}function R0(e,t,n,r){if(N0(e))return j_e(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new O(t,{error:n,error_description:r})}function z0(e){return`${e.context.authCookies.sessionToken.name}.oauth_logout_confirmation`}function B0(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:A_e(e),sameSite:`lax`}}async function V0(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+3e5};await e.setSignedCookie(z0(e),JSON.stringify(r),e.context.secret,B0(e,300))}async function M_e(e){let t=await e.getSignedCookie(z0(e),e.context.secret);if(typeof t!=`string`)return null;try{let e=JSON.parse(t);if(typeof e!=`object`||!e)return null;let n=e;return n.sessionId!==void 0&&(typeof n.sessionId!=`string`||n.sessionId.length===0)||n.clientId!==void 0&&(typeof n.clientId!=`string`||n.clientId.length===0)||n.postLogoutRedirectUri!==void 0&&(typeof n.postLogoutRedirectUri!=`string`||n.postLogoutRedirectUri.length===0)||n.state!==void 0&&typeof n.state!=`string`||n.redirectInvalid!==void 0&&typeof n.redirectInvalid!=`boolean`||n.postLogoutRedirectUri!==void 0&&n.clientId===void 0||typeof n.expiresAt!=`number`||!Number.isFinite(n.expiresAt)?null:{...typeof n.sessionId==`string`?{sessionId:n.sessionId}:{},...typeof n.clientId==`string`?{clientId:n.clientId}:{},...typeof n.postLogoutRedirectUri==`string`?{postLogoutRedirectUri:n.postLogoutRedirectUri}:{},...typeof n.state==`string`?{state:n.state}:{},...typeof n.redirectInvalid==`boolean`?{redirectInvalid:n.redirectInvalid}:{},expiresAt:n.expiresAt}}catch{return null}}function H0(e){e.setCookie(z0(e),``,B0(e,0))}async function U0(e){let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(typeof t!=`string`||t.length===0)return null;try{let n=await e.context.internalAdapter.findSession(t);return n?{session:n.session}:null}catch(t){throw e.context.logger.error(`Failed to read the current logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function N_e(e,t){try{return await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:t}]})}catch(t){throw e.context.logger.error(`Failed to read the hinted logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function W0(e,t){if(typeof t.token!=`string`||t.token.length===0)throw new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`});try{await e.context.internalAdapter.deleteSession(t.token)}catch(t){throw e.context.logger.error(`Failed to delete the logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`})}}async function G0(e,t,n){try{return await e1(e,t,n)}catch(t){throw e.context.logger.error(`Failed to resolve the logout client`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to resolve the logout client`})}}function K0(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function P_e(e){if(typeof e.aud==`string`&&e.aud.length>0)return e.aud;if(typeof e.azp==`string`&&e.azp.length>0)return e.azp;let t=K0(e.aud);return t.length===1?t[0]:null}async function F_e(e,t,n,r){if(r)return G0(e,t,r);let i;try{i=mI(n)}catch{return null}let a=P_e(i);return a?G0(e,t,a):null}async function I_e(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await r1(e,t.storeClientSecret,r.clientSecret),{payload:o}=await IF(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=K$(e.context).options,{payload:r}=await IF(n,cI(await FZ(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==d4(e,t)||!K0(i.aud).includes(r.clientId)||typeof i.sid!=`string`||i.sid.length===0||typeof i.sub!=`string`||i.sub.length===0?null:i}catch{return null}}function q0(e,t,n){if(!t)return{invalid:!1};if(!e.postLogoutRedirectUris?.includes(t))return{invalid:!0};if(!n)return{uri:t,invalid:!1};try{let e=new URL(t);return e.searchParams.set(`state`,n),{uri:e.toString(),invalid:!1}}catch{return{invalid:!0}}}function J0(e,t){return t.post_logout_redirect_uri?q0(e,t.post_logout_redirect_uri,t.state).invalid?{redirectInvalid:!0}:{clientId:e.clientId,postLogoutRedirectUri:t.post_logout_redirect_uri,...t.state===void 0?{}:{state:t.state}}:{}}async function L_e(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await G0(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:q0(r,n.postLogoutRedirectUri,n.state)}async function Y0(e,t,n={}){return t?N0(e)?(await V0(e,t.session.id,n),I0(e)):R0(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):N0(e)?(await V0(e,void 0,n),I0(e)):R0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function R_e(e,t){let n=await M_e(e),r=await U0(e);if(!n||n.expiresAt<=Date.now())return R0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await L_e(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?R0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await W0(e,r.session),fq(e),H0(e),i.uri?c4(e,i.uri):N0(e)?L0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(H0(e),i.uri?c4(e,i.uri):N0(e)?L0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):R0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function z_e(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await U0(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await G0(e,t,i.client_id);if(!r)return R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return R0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=J0(r,i)}return Y0(e,a,n)}let o=await F_e(e,t,i.id_token_hint,i.client_id);if(!o)return a&&N0(e)?Y0(e,a):R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return R0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await I_e(e,t,i.id_token_hint,o);if(!s)return a&&N0(e)?Y0(e,a,i.client_id?J0(o,i):{}):R0(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await N_e(e,c),u=a?.session.id===c;if(a&&!u)return Y0(e,a,J0(o,i));let d=q0(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await W0(e,f),u&&fq(e),H0(e),d.uri?c4(e,d.uri):N0(e)?L0(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function B_e(e,t){return R_e(e,t)}function X0(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:u4(t?.jwt?.issuer??r),authorization_endpoint:`${r}/oauth2/authorize`,token_endpoint:`${r}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:t?.jwks?.remoteUrl??`${r}${t?.jwks?.jwksPath??`/jwks`}`,registration_endpoint:n?.dynamic_client_registration_supported?`${r}/oauth2/register`:void 0,introspection_endpoint:`${r}/oauth2/introspect`,revocation_endpoint:`${r}/oauth2/revoke`,response_types_supported:n?.grant_types_supported&&!n.grant_types_supported.includes(`authorization_code`)?[]:[`code`],response_modes_supported:[`query`],grant_types_supported:n?.grant_types_supported??[`authorization_code`,`client_credentials`,`refresh_token`],token_endpoint_auth_methods_supported:n?.token_endpoint_auth_methods_supported??[...n?.public_client_supported?[`none`]:[],`client_secret_basic`,`client_secret_post`,`private_key_jwt`],token_endpoint_auth_signing_alg_values_supported:[...iX],introspection_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],introspection_endpoint_auth_signing_alg_values_supported:[...iX],revocation_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],revocation_endpoint_auth_signing_alg_values_supported:[...iX],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...eZ],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function Z0(e,t){let n=t.disableJwtPlugin?void 0:K$(e.context).options,r=z$(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:X0(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:B$(t),token_endpoint_auth_methods_supported:H$(t,{includeNone:i}),endpoint_auth_methods_supported:H$(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function Q0(e,t){let{clientDiscoveries:n,authMetadata:r}=Z0(e,t);return W$(e,t,`oauth-authorization-server`,{...t1(n),...r})}function $0(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=Z0(e,t),o={...a,claims_supported:R1(t),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:t.pairwiseSecret?[`public`,`pairwise`]:[`public`],acr_values_supported:[`0`],id_token_signing_alg_values_supported:(()=>{if(t.disableJwtPlugin)return[`HS256`];let e=r?.jwks?.keyPairConfig?.alg??`EdDSA`,n=r?.jwks?.keyPairConfigs?.map(e=>e.alg)??[];return Array.from(/* @__PURE__ */ new Set([e,...n]))})(),end_session_endpoint:`${n}/oauth2/end-session`,request_parameter_supported:!1,request_uri_parameter_supported:!1,prompt_values_supported:[`login`,`consent`,`create`,`select_account`,`none`]};return W$(e,t,`openid-configuration`,{...t1(i),...o})}function e2(e,t){let n=new Headers(t);return n.has(`Cache-Control`)||n.set(`Cache-Control`,`public, max-age=15, stale-while-revalidate=15, stale-if-error=86400`),n.set(`Content-Type`,`application/json`),new Response(JSON.stringify(e),{status:200,headers:n})}function t2(e,t,n){let{redirectOnError:r,onValidationError:i,errorCodesByField:a,defaultError:o=`invalid_request`,...s}=t;if(!r)return X(e,{...s,onValidationError:async e=>{throw i&&await i(e),new O(`BAD_REQUEST`,{...n2(e.issues,a,o)})}},n);let c=r,{body:l,query:u,...d}=s;async function f(e,t,n){if(!n)return{ok:!0};let r=await n.safeParseAsync(e[t]??{});return r.success?(e[t]=r.data,{ok:!0}):(i&&await i({message:r.error.message,issues:r.error.issues}),{ok:!1,response:c({...n2(r.error.issues,a,o),ctx:e})})}return X(e,d,async e=>{let t=await f(e,`body`,l);if(!t.ok)return t.response;let r=await f(e,`query`,u);return r.ok?n(e):r.response})}function n2(e,t,n=`invalid_request`){let r=e[0];if(!r)return{error:n,error_description:`Invalid request.`};let i=r.path?.[0],a=typeof i==`string`?i:void 0,o=a?t?.[a]:void 0,s=r.path?.length?ke(r.path):``;return{error:V_e(r,o,n),error_description:U_e(r,s)}}function V_e(e,t,n){return typeof t==`string`?t:H_e(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function H_e(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function U_e(e,t){if(!t)return e.message;if(e.code===`invalid_type`)return e.message.endsWith(`received undefined`)?`${t} is required`:e.message.endsWith(`received array`)?`${t} must not appear more than once`:`${t} must be a ${e.expected??`valid value`}`;if(e.code===`invalid_value`){let n=e.values;if(Array.isArray(n)&&n.length>0)return`${t} must be one of: ${n.join(`, `)}`}return`${t}: ${e.message}`}const W_e=e=>Hq(async t=>{if(!e.allowPublicClientPrelogin)throw new E(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await Q$(n,t.context.secret))throw new E(`UNAUTHORIZED`,{error:`invalid_signature`})}),r2={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},G_e=[`Ed25519`],K_e=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function i2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a2(e,t){return typeof e[t]==`string`&&e[t].length>0}function o2(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(r2,e)}function s2(e){return G_e.some(t=>t===e)}function q_e(e){switch(e.kty){case`RSA`:return a2(e,`n`)&&a2(e,`e`);case`EC`:return o2(e.crv)&&a2(e,`x`)&&a2(e,`y`);case`OKP`:return s2(e.crv)&&a2(e,`x`);default:return!1}}function J_e(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!iX.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return o2(e.crv)&&r2[e.crv]===e.alg;case`OKP`:return s2(e.crv)&&e.alg===`EdDSA`;default:return!1}}function c2(e){let t=i2(e)&&Array.isArray(e.keys)?e.keys:void 0;if(!t?.length)return{valid:!1,error:`jwks must be an RFC 7517 JWK Set object with a non-empty keys array`};for(let e of t){if(!i2(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||K_e.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!q_e(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!J_e(e))return{valid:!1,error:`jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve`}}return{valid:!0,jwks:{keys:t}}}function l2(e){let t=c2(e);if(!t.valid)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}const Y_e=Object.freeze(Object.keys({clientId:!0,clientSecret:!0,clientDiscoveryId:!0,disabled:!0,scopes:!0,clientCredentialsScopes:!0,userId:!0,createdAt:!0,updatedAt:!0,expiresAt:!0,name:!0,uri:!0,icon:!0,contacts:!0,tos:!0,policy:!0,softwareId:!0,softwareVersion:!0,softwareStatement:!0,redirectUris:!0,postLogoutRedirectUris:!0,backchannelLogoutUri:!0,backchannelLogoutSessionRequired:!0,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),X_e=/* @__PURE__ */ `client_id.client_secret.client_secret_expires_at.scope.user_id.client_id_issued_at.client_name.client_uri.logo_uri.contacts.tos_uri.policy_uri.jwks.jwks_uri.software_id.software_version.software_statement.redirect_uris.post_logout_redirect_uris.backchannel_logout_uri.backchannel_logout_session_required.token_endpoint_auth_method.grant_types.response_types.application_type.disabled.skip_consent.enable_end_session.require_pkce.dpop_bound_access_tokens.subject_type.reference_id`.split(`.`),Z_e=/* @__PURE__ */ new Set([...Y_e,...X_e,`public`,`type`,`resources`,`client_credentials_scopes`]),Q_e=/* @__PURE__ */ new Set(/* @__PURE__ */ `disabled.client_secret.client_secret_expires_at.client_id_issued_at.skip_consent.enable_end_session.require_pkce.reference_id.user_id.resources.clientSecret.clientDiscoveryId.skipConsent.enableEndSession.requirePKCE.referenceId.userId.clientId.applicationType.tokenEndpointAuthMethod.redirectUris.postLogoutRedirectUris.grantTypes.responseTypes.scopes.expiresAt.createdAt.updatedAt.softwareId.softwareVersion.softwareStatement.backchannelLogoutUri.backchannelLogoutSessionRequired.jwksUri.dpopBoundAccessTokens.subjectType`.split(`.`));function u2(e){return Q_e.has(e)}function d2(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!Z_e.has(e)))}async function f2(e,t,n,r,i){if(!t)throw new E(`UNAUTHORIZED`);if(!e.headers)throw new E(`BAD_REQUEST`);if(r===`configure-client-credentials-scopes`&&!n.clientPrivileges||n.clientPrivileges&&!await n.clientPrivileges({headers:e.headers,action:r,session:t.session,user:t.user,clientId:i}))throw new E(`UNAUTHORIZED`)}async function p2(e,t,n,r,i){if(!t)throw new E(`UNAUTHORIZED`);if(!e.headers)throw new E(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new E(`UNAUTHORIZED`)}var $_e=/* @__PURE__ */ O$({consumeClientAssertion:()=>C2,isPrivateHostname:()=>b2,verifyClientAssertion:()=>w2});const m2=/* @__PURE__ */ new WeakMap,h2=65536,eve=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function g2(e,t,n,r){if(e.set(t,{jwks:n,fetchedAt:r}),e.size>500){let t=e.keys().next().value;t!==void 0&&e.delete(t)}}function _2(e){let t=m2.get(e);if(t)return t;let n=/* @__PURE__ */ new Map;return m2.set(e,n),n}function v2(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}const y2=[...iX];function b2(e){return!CY(e)}function tve(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(b2(r.hostname))throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not point to a private or reserved address`,error:`invalid_client`});if(!(n&&r.origin===n)&&!e.context.isTrustedOrigin(r.href))throw new O(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function nve(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function rve(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>h2)throw await e.body?.cancel(),Error(`JWKS response exceeds 64 KiB`);if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;if(i+=t.byteLength,i>h2)throw await n.cancel(),Error(`JWKS response exceeds 64 KiB`);r.push(t)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)}async function x2(e,t=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);try{let r=await t(e,{signal:n.signal,headers:{accept:`application/json`},redirect:`error`});if(r.redirected)throw Error(`JWKS fetch redirected`);if(r.status!==200)throw Error(`JWKS fetch returned ${r.status}`);let i=r.headers.get(`content-type`);if(!i||!eve.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await rve(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=c2(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function S2(){return new O(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function ive(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new O(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?z$(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new O(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});tve(e,n.jwksUri,n.clientDiscoveryId?nve(n.clientId):void 0);let i=Date.now(),a=v2(n),o=_2(t),s=o.get(a);if(s&&i-s.fetchedAt<3e5)return s.jwks;let c;try{c=await x2(n.jwksUri,r?.fetchClientMetadataResource)}catch{if(s&&i-s.fetchedAt<6e5)return s.jwks;throw S2()}if(!c.valid)throw S2();return g2(o,a,c.jwks,i),c.jwks}async function ave(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?z$(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await x2(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(g2(_2(e),v2(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function C2(e,t,n){let{namespace:r,payload:i,expectedAudience:a}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud==null?[]:[i.aud]).includes(a))throw new O(`BAD_REQUEST`,{error_description:`client assertion aud does not match the endpoint`,error:`invalid_client`});let o=t.assertionMaxLifetime??300,s=Math.floor(Date.now()/1e3);if(typeof i.exp!=`number`)throw new O(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new O(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new O(`BAD_REQUEST`,{error_description:`client assertion exp is too far in the future (max ${o}s)`,error:`invalid_client`});if(typeof i.iat==`number`&&s-i.iat>o)throw new O(`BAD_REQUEST`,{error_description:`client assertion iat is too far in the past (max ${o}s)`,error:`invalid_client`});if(typeof i.jti!=`string`||i.jti.length===0)throw new O(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await FU(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=we(new Uint8Array(c).slice(0,24),e.context.options);try{await e.context.adapter.create({model:`oauthClientAssertion`,data:{id:l,expiresAt:/* @__PURE__ */ new Date(i.exp*1e3)},forceAllowId:!0})}catch(t){let n=!1;try{n=!!await e.context.adapter.findOne({model:`oauthClientAssertion`,where:[{field:`id`,value:l}]})}catch{}throw n?new O(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function w2(e,t,n,r,i,a,o){if(r!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new O(`BAD_REQUEST`,{error_description:`unsupported client_assertion_type`,error:`invalid_client`});let s;try{s=pI(n)}catch{throw new O(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!s.alg||!y2.includes(s.alg))throw new O(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${s.alg}`,error:`invalid_client`});let c;try{c=mI(n)}catch{throw new O(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT payload`,error:`invalid_client`})}let l=c.sub??c.iss;if(!l)throw new O(`BAD_REQUEST`,{error_description:`client assertion must contain sub or iss claim identifying the client`,error:`invalid_client`});if(i&&i!==l)throw new O(`BAD_REQUEST`,{error_description:`client_id in body does not match assertion sub/iss`,error:`invalid_client`});let u=await e1(e,t,l);if(!u)throw new O(`BAD_REQUEST`,{error_description:`client not found`,error:`invalid_client`});if(u.disabled)throw new O(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(u.tokenEndpointAuthMethod!==`private_key_jwt`)throw new O(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});o?.assertClient?.(u);let d=await ive(e,t,u),f=a??`${e.context.baseURL}/oauth2/token`,p=d4(e,t),m=o?.endpointAudienceOnly?[f]:[.../* @__PURE__ */ new Set([f,p])],h={issuer:l,subject:l,audience:m,algorithms:y2},g;try{({payload:g}=await $F(n,cI(d),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await ave(t,u);if(e)try{({payload:g}=await $F(n,cI(e),h))}catch{throw new O(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new O(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new O(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}let _=(Array.isArray(g.aud)?g.aud:[g.aud]).find(e=>typeof e==`string`&&m.includes(e));return await C2(e,t,{namespace:`private_key_jwt:${l}`,payload:g,expectedAudience:_}),{clientId:l,client:u}}function T2(e,t,n){return new O(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...zq})}async function ove(e,t,n){let r=e.headers,i;try{i=Hhe(r?.get(`authorization`))}catch{throw T2(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw T2(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);let a;try{a=await t.validateInitialAccessToken({initialAccessToken:i,headers:r,clientMetadata:n})}catch(e){throw e instanceof O?e:new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Initial access token validation failed`})}if(!a)throw T2(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}const sve=[`authorization_code`];function E2(e){return[.../* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function D2(e){let t=e.grant_types??[...sve];if(t.length>0)return t;throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function cve(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function O2(e,t){let n=new Set(B$(e)),r=t.filter(e=>n.has(e));if(r.length===0)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${t.join(`, `)}`});return r}function k2(e,t=`web`){let n=D2(e);return{...e,token_endpoint_auth_method:e.token_endpoint_auth_method??`client_secret_basic`,application_type:e.application_type??(t===null?void 0:t),grant_types:n,response_types:cve(e,n)}}function lve(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function uve(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function A2(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(e=>uve(e)||M2(e))?`native`:`web`:n}function j2(e){throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function dve(e){let t=/^http:\/\/([^/?#]*)/i.exec(e)?.[1];if(!t)return null;let n=t.slice(t.lastIndexOf(`@`)+1);if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e<0?null:n.slice(0,e+1).toLowerCase()}return(n.split(`:`)[0]??``).toLowerCase()}function M2(e){let t=dve(e);return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}function fve(e,t){let n=/* @__PURE__ */ new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let e of t)if(!n.has(e))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`})}async function pve(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[.../* @__PURE__ */ new Set([...r,...n])];for(let n of i){let r=await Z1(e,t,n);if(!r)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return i}function mve(e,t){let n;try{n=new URL(e)}catch{j2(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&j2(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&j2(`redirect URI localhost must not include trailing dots: ${e}`);let a=xY(n.hostname)||n.hostname===`localhost`;t===`web`?(!i||a)&&j2(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&j2(`native clients must not use https loopback redirect URIs: ${e}`):r?M2(e)||j2(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):D1(n)||j2(`native private-use redirect URI schemes must not use a reserved scheme; they must be an authority-free reverse-domain URI or a custom-scheme URI with a host and a path: ${e}`)}async function hve(e,t){let n=e.body;if(!t.allowDynamicClientRegistration)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let r=await HJ(e),i=r?void 0:await ove(e,t,n),a=!!i;if(!(r||a||t.allowUnauthenticatedClientRegistration))throw new E(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...zq});let o=n.grant_types?.length?O2(t,n.grant_types):n.grant_types,s=n.grant_types?.includes(`authorization_code`)&&!o?.includes(`authorization_code`),c={...n,grant_types:o,response_types:s?void 0:n.response_types};if(!r&&!a&&c.grant_types?.includes(`client_credentials`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials grant requires authenticated registration`});let l=Array.isArray(n.resources)?n.resources.filter(e=>typeof e==`string`&&e.length>0):[];r&&await f2(e,r,t,`create`);let u=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),d=await R2(e,t,{metadata:c,registrationSource:`dynamic`,userId:u?void 0:r?.session.userId,referenceId:u,requestedResources:l});return e.setStatus(201),e.json(d)}async function N2(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=k2(e,r?null:n?.registrationSource===`dynamic`?A2(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(H$(t,{includeNone:!0})).has(a))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported token_endpoint_auth_method ${a}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=`boolean`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`dpop_bound_access_tokens must be a boolean`});let o=i.grant_types??[],s=i.response_types,c=i.application_type;if(c!==void 0&&c!==`web`&&c!==`native`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`application_type must be web or native`});if(o.includes(`authorization_code`)&&(!i.redirect_uris||i.redirect_uris.length===0))throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:`Redirect URIs are required for authorization_code and implicit grant types`});for(let e of i.redirect_uris??[])mve(e,c??(r?`native`:`web`));if(r)O2(t,o);else{let e=new Set(B$(t));for(let t of o)if(!e.has(t))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${t}`})}if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'authorization_code' grant type is used, 'code' response type must be included`});if(!o.includes(`authorization_code`)&&s?.includes(`code`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'code' response type is used, 'authorization_code' grant type must be included`});if(i.subject_type!==void 0){if(i.subject_type!==`public`&&i.subject_type!==`pairwise`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});if(i.subject_type===`pairwise`&&i.redirect_uris?.some(lve))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients cannot use custom-scheme redirect URIs that include a host`});if(i.subject_type===`pairwise`&&i.redirect_uris&&i.redirect_uris.length>1&&new Set(i.redirect_uris.map(e=>new URL(e).host)).size>1)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host.`})}let l=(i?.scope)?.split(` `).filter(e=>e.length),u=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,d=u?E2(t):t.scopes;if(d){let e=new Set(d);for(let t of l??[])if(!e?.has(t))throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(u&&i.require_pkce===!1)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pkce is required for registered clients.`});if(i.jwks||i.jwks_uri){if(i.jwks&&i.jwks_uri)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks and jwks_uri are mutually exclusive`});if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.protocol!==`https:`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(b2(e.hostname))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not point to a private or reserved address`});if(n?.ctx&&!n.ctx.context.isTrustedOrigin(e.href)){let t=typeof i.client_id==`string`?i.client_id:void 0;if(!(r&&t!==void 0&&URL.canParse(t)&&new URL(t).origin===e.origin))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin`})}}catch(e){throw e instanceof E?e:new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&l2(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`private_key_jwt requires either jwks or jwks_uri`});if(i.backchannel_logout_uri!==void 0){if(t.disableJwtPlugin)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)`});let e;try{e=new URL(i.backchannel_logout_uri)}catch{throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must be an absolute URL`})}if(i.backchannel_logout_uri.includes(`#`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not include a fragment component`});if(e.protocol!==`https:`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must use https`});if(e.username||e.password)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not contain credentials`});if(b2(e.hostname))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not point to a private or reserved address`})}}const P2=Symbol(`client-registration-collision`);function F2(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[P2]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function I2(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=k2(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?A2(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=U$(t,i.token_endpoint_auth_method);await N2(i,t,{registrationSource:n.registrationSource,ctx:e});let c=n.clientId??t.generateClientId?.()??ZH(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||ZH(32,`a-z`,`A-Z`),u=l?await i1(e,t,l):void 0,d=n.registrationSource===`dynamic`&&!a&&t.clientRegistrationRequirePKCE===!1,f=i.require_pkce??(!d&&void 0),p=Math.floor(Date.now()/1e3),{resources:m,...h}=n.registrationSource===`dynamic`||n.registrationSource===`clientMetadataDocument`?{...i,scope:E2(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=H2({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?x$(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:c,client_secret:u,client_id_issued_at:p,require_pkce:f,user_id:g?.referenceId?void 0:g?.userId,reference_id:g?.referenceId});_.clientCredentialsScopes=n.registrationSource===`managed`?n.clientCredentialsScopes??[]:[],_.clientDiscoveryId=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,n.registrationSource===`clientMetadataDocument`&&i.application_type===void 0&&(_.applicationType=null);let v=n.registrationSource===`clientMetadataDocument`?[]:n.requestedResources??[];n.registrationSource===`dynamic`&&fve(t,v);let y=await pve(e,t,v),b=t.schema?.oauthClient?.modelName??`oauthClient`,x=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,S=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,ee=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,C=await DH(e.context.adapter,async()=>{let t=await TH(e.context.adapter),r,i=!1;if(S){let{clientCredentialsScopes:e,disabled:n,skipConsent:i,enableEndSession:a,...o}=_,s=await t.update({model:b,where:[{field:`clientId`,value:c},{field:`clientDiscoveryId`,value:ee}],update:{...o,createdAt:S.createdAt,updatedAt:/* @__PURE__ */ new Date(p*1e3)}});if(!s)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=s}else{try{r=await t.create({model:b,data:{..._,createdAt:/* @__PURE__ */ new Date(p*1e3),updatedAt:/* @__PURE__ */ new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&B2(e)?{[P2]:!0,kind:`oauth-client-row-unique`,clientId:c,cause:e}:e}i=!0}let a=y.length===0?[]:await t.findMany({model:x,where:[{field:`clientId`,value:c}]}),o=new Set(a.map(e=>e.resourceId)),s=/* @__PURE__ */ new Date;for(let e of y)if(!o.has(e))try{await t.create({model:x,data:{clientId:c,resourceId:e,createdAt:s}})}catch(t){throw n.registrationSource===`clientMetadataDocument`&&B2(t)?{[P2]:!0,kind:`oauth-client-resource-link-unique`,clientId:c,resourceId:e,cause:t}:t}return{client:r,created:i}});return{client:C.client,clientSecret:l,resources:y,created:C.created}}function L2(e,t){let n=U2({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function gve(e,t){return{...L2(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function R2(e,t,n){return L2(await I2(e,t,n),t)}async function _ve(e,t,n){return gve(await I2(e,t,n),t)}function vve(e,t){if(e&&e.clientDiscoveryId!==t)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}async function z2(e,t,n){if(vve(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Documents cannot register a back-channel logout target`});if((n.metadata.token_endpoint_auth_method??`none`)!==`none`&&n.metadata.token_endpoint_auth_method!==`private_key_jwt`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Document clients cannot use a shared secret`});let r={...n,metadata:{...n.metadata,token_endpoint_auth_method:n.metadata.token_endpoint_auth_method??`none`,client_secret:void 0,client_secret_expires_at:void 0},registrationSource:`clientMetadataDocument`};try{return await I2(e,t,r)}catch(i){if(!F2(i))throw i;let a=t.schema?.oauthClient?.modelName??`oauthClient`,o=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,s=await e.context.adapter.findOne({model:a,where:[{field:`clientId`,value:n.clientId}]});if(i.clientId!==n.clientId||!s||s.clientDiscoveryId!==n.clientDiscoveryId||i.kind===`oauth-client-resource-link-unique`&&!await e.context.adapter.findOne({model:o,where:[{field:`clientId`,value:i.clientId},{field:`resourceId`,value:i.resourceId}]}))throw i.cause;try{return await I2(e,t,{...r,existingClient:s})}catch(e){throw F2(e)?e.cause:e}}}function B2(e){if(!e||typeof e!=`object`)return!1;let t=e,n=String(t.code??t.errno??``);return[`1062`,`11000`,`23505`,`ER_DUP_ENTRY`,`P2002`,`SQLITE_CONSTRAINT_UNIQUE`].includes(n)||t.name===`MongoServerError`&&t.code===11e3?!0:typeof t.message==`string`&&/(?:duplicate|unique constraint|unique key)/i.test(t.message)}async function V2(e,t,n){let r=await HJ(e);if(await f2(e,r,t,`create`),!r)throw new E(`UNAUTHORIZED`);let i=t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0,{client_credentials_scopes:a,...o}=e.body,s=n?.admin?i0(a??[]):[];a0(s,D2(o),o.token_endpoint_auth_method,t),s.length>0&&await f2(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await p2(e,r,t,`link`,n);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s,...c?{requestedResources:c}:{}},u=n?.admin?await _ve(e,t,l):await R2(e,t,l);return e.setStatus(201),e.json(u)}function H2(e){let{client_id:t,client_secret:n,client_secret_expires_at:r,scope:i,user_id:a,client_id_issued_at:o,client_name:s,client_uri:c,logo_uri:l,contacts:u,tos_uri:d,policy_uri:f,jwks:p,jwks_uri:m,software_id:h,software_version:g,software_statement:_,redirect_uris:v,post_logout_redirect_uris:y,backchannel_logout_uri:b,backchannel_logout_session_required:x,token_endpoint_auth_method:S,grant_types:ee,response_types:C,application_type:te,disabled:w,skip_consent:ne,enable_end_session:T,require_pkce:re,dpop_bound_access_tokens:ie,subject_type:ae,reference_id:oe,metadata:se}=e,ce=r?/* @__PURE__ */ new Date(Number(r)*1e3):void 0,le=o?/* @__PURE__ */ new Date(o*1e3):void 0,ue=i?.split(` `),de=d2(se??{}),fe=de&&Object.keys(de).length?JSON.stringify(de):void 0;return{clientId:t,clientSecret:n,disabled:w,scopes:ue,userId:a,createdAt:le,expiresAt:ce,name:s,uri:c,icon:l,contacts:u,tos:d,policy:f,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:ee,responseTypes:C,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:te,skipConsent:ne,enableEndSession:T,requirePKCE:re,dpopBoundAccessTokens:ie,subjectType:ae,referenceId:oe,metadata:fe}}function U2(e){let{clientId:t,clientSecret:n,disabled:r,scopes:i,userId:a,createdAt:o,updatedAt:s,expiresAt:c,name:l,uri:u,icon:d,contacts:f,tos:p,policy:m,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:ee,responseTypes:C,applicationType:te,jwks:w,jwksUri:ne,skipConsent:T,enableEndSession:re,requirePKCE:ie,dpopBoundAccessTokens:ae,subjectType:oe,referenceId:se,metadata:ce}=e,le=c?Math.round(new Date(c).getTime()/1e3):void 0,ue=o?Math.round(new Date(o).getTime()/1e3):void 0,de=i?.join(` `);return{...d2(m1(ce)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?le??0:void 0,scope:de??void 0,user_id:a??void 0,client_id_issued_at:ue??void 0,client_name:l??void 0,client_uri:u??void 0,logo_uri:d??void 0,contacts:f??void 0,tos_uri:p??void 0,policy_uri:m??void 0,jwks:w?JSON.parse(w):void 0,jwks_uri:ne??void 0,software_id:h??void 0,software_version:g??void 0,software_statement:_??void 0,redirect_uris:v??[],post_logout_redirect_uris:y??void 0,backchannel_logout_uri:b??void 0,backchannel_logout_session_required:x??void 0,token_endpoint_auth_method:S??void 0,grant_types:ee??void 0,response_types:C??void 0,application_type:te??void 0,disabled:r??void 0,skip_consent:T??void 0,enable_end_session:re??void 0,require_pkce:ie??void 0,dpop_bound_access_tokens:ae??void 0,subject_type:oe??void 0,reference_id:se??void 0}}async function yve(e,t){let n=await HJ(e);if(await f2(e,n,t,`read`,e.query.client_id),!n)throw new E(`UNAUTHORIZED`);let r=await e1(e,t,e.query.client_id);if(!r)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);let i=U2(r);return i.client_secret=void 0,i}async function W2(e,t,n){let r=await e1(e,t,n);if(!r||r.disabled)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return U2({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function bve(e,t){let n=await HJ(e);if(await f2(e,n,t,`list`),!n)throw new E(`UNAUTHORIZED`);let r=await t.clientReference?.(n);if(r)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`referenceId`,value:r}]}).then(e=>e?e.map(e=>{let t=U2(e);return t.client_secret=void 0,t}):null);if(n.user.id)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`userId`,value:n.user.id}]}).then(e=>e?e.map(e=>{let t=U2(e);return t.client_secret=void 0,t}):null);throw new E(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function xve(e,t){let n=await HJ(e);if(await f2(e,n,t,`delete`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;$$(t,r);let i=await e1(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function G2(e,t,n){let r=await HJ(e);if(await f2(e,r,t,`update`,e.body.client_id),!r)throw new E(`UNAUTHORIZED`);let i=e.body.client_id;$$(t,i);let a=await e1(e,t,i);if(!a)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let{client_credentials_scopes:o,...s}=e.body.update,c=a.userId?a.userId===r.user.id:a.referenceId&&t.clientReference?a.referenceId===await t.clientReference(r):!1,l=!c&&n?.admin&&o!==void 0&&Object.keys(s).length===0;if(!c&&!l)throw new E(`UNAUTHORIZED`);if(l&&await f2(e,r,t,`configure-client-credentials-scopes`,i),Object.keys(s).length===0&&o===void 0){let e=U2(a);return e.client_secret=void 0,n?.admin?{...e,client_credentials_scopes:[...a.clientCredentialsScopes??[]]}:e}let u=s.grant_types??a.grantTypes??[],d=s.token_endpoint_auth_method??a.tokenEndpointAuthMethod,f=o===void 0?void 0:i0(o);f!==void 0&&(a0(f,u,d,t),f.length>0&&!l&&await f2(e,r,t,`configure-client-credentials-scopes`,i)),await N2({...U2(a),...s},t,{ctx:e});let p={...H2(s)};!u.includes(`client_credentials`)||d===`none`?p.clientCredentialsScopes=[]:f!==void 0&&(p.clientCredentialsScopes=f),s.token_endpoint_auth_method&&(s.token_endpoint_auth_method===`private_key_jwt`?p.clientSecret=null:(p.jwks=null,p.jwksUri=null,p.clientSecret||=await i1(e,t,t.generateClientSecret?.()||ZH(32,`a-z`,`A-Z`))));let m=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...p,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!m)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let h=U2(m);return h.client_secret=void 0,n?.admin?{...h,client_credentials_scopes:[...m.clientCredentialsScopes??[]]}:h}async function Sve(e,t){let n=await HJ(e);if(await f2(e,n,t,`rotate`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;$$(t,r);let i=await e1(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new E(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||ZH(32,`a-z`,`A-Z`),o=a?await i1(e,t,a):void 0,s=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:r}],update:{clientSecret:o,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!s)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return U2({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}async function Cve(e,t){if(!t.allowClientKeyRotation)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client key rotation is disabled`});let{body:n}=e;l2(n.jwks);let{client:r}=await w2(e,t,n.client_assertion,n.client_assertion_type,void 0,n0({context:e.context,request:void 0},`/oauth2/client/rotate-keys`),{endpointAudienceOnly:!0,assertClient:e=>wve(t,e)});if(!await e.context.adapter.incrementOne({model:`oauthClient`,where:[{field:`clientId`,value:r.clientId},{field:`jwks`,value:r.jwks}],increment:{},set:{jwks:JSON.stringify(n.jwks),updatedAt:/* @__PURE__ */ new Date}}))throw new E(`CONFLICT`,{error:`invalid_request`,error_description:`client keys changed while rotating; retry with a fresh client assertion`});return{client_id:r.clientId,jwks:n.jwks}}function wve(e,t){if($$(e,t.clientId),t.clientDiscoveryId||t.jwksUri||!t.jwks)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client keys are not stored inline; rotate them where the client publishes them`})}const K2=k().trim().min(1),q2=Be(k().trim().min(1)).min(1),Tve=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),token_endpoint_auth_method:K2.optional(),application_type:Ze([`web`,`native`]).optional(),jwks:V1.optional(),jwks_uri:k().optional(),grant_types:q2.optional(),client_credentials_scopes:Be(k().trim().min(1)).optional(),resources:Be(B1).optional(),response_types:Be(Ze([`code`])).optional(),client_secret_expires_at:Ae([k(),Le()]).optional().default(0),skip_consent:Je().optional(),enable_end_session:Je().optional(),require_pkce:Je().optional(),dpop_bound_access_tokens:Je().optional(),subject_type:Ze([`public`,`pairwise`]).optional(),metadata:ze(k(),rt()).optional()}),metadata:{noStore:!0,SERVER_ONLY:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},client_credentials_scopes:{type:`array`,items:{type:`string`},description:`Server-authorized scope ceiling for client_credentials tokens`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},require_pkce:{type:`boolean`,description:`Whether the client requires PKCE`,default:!0},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>V2(t,e,{admin:!0})),Eve=e=>X(`/oauth2/create-client`,{method:`POST`,use:[WJ],body:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),token_endpoint_auth_method:K2.optional(),application_type:Ze([`web`,`native`]).optional(),jwks:V1.optional(),jwks_uri:k().optional(),grant_types:q2.optional(),response_types:Be(Ze([`code`])).optional(),dpop_bound_access_tokens:Je().optional()}),metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>V2(t,e)),Dve=e=>X(`/oauth2/get-client`,{method:`GET`,use:[WJ],query:A({client_id:k()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>yve(t,e)),Ove=e=>X(`/oauth2/public-client`,{method:`GET`,use:[WJ],query:A({client_id:k()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return W2(t,e,n)}),kve=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[W_e(e)],body:A({client_id:k(),oauth_query:k().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return W2(t,e,n)}),Ave=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[WJ],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>bve(t,e)),jve=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:A({client_id:k(),update:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),application_type:Ze([`web`,`native`]).optional(),grant_types:q2.optional(),client_credentials_scopes:Be(k().trim().min(1)).optional(),response_types:Be(Ze([`code`])).optional(),client_secret_expires_at:Ae([k(),Le()]).optional(),skip_consent:Je().optional(),enable_end_session:Je().optional(),disabled:Je().optional(),dpop_bound_access_tokens:Je().optional(),metadata:ze(k(),rt()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>G2(t,e,{admin:!0})),Mve=e=>X(`/oauth2/update-client`,{method:`POST`,use:[WJ],body:A({client_id:k(),update:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),application_type:Ze([`web`,`native`]).optional(),grant_types:q2.optional(),response_types:Be(Ze([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>G2(t,e)),Nve=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[WJ],body:A({client_id:k()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>Sve(t,e)),Pve=e=>t2(`/oauth2/client/rotate-keys`,{method:`POST`,body:A({client_assertion:k(),client_assertion_type:k(),jwks:V1}),errorCodesByField:{client_assertion:`invalid_client`,client_assertion_type:`invalid_client`,jwks:`invalid_client_metadata`},metadata:{noStore:!0,openapi:{description:`Replaces the signing keys of a private_key_jwt client. The request is authenticated by a client assertion signed with one of the client's current keys and addressed to this endpoint. Keys left out of the new set stop verifying at once.`}}},async t=>Cve(t,e)),Fve=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[WJ],body:A({client_id:k()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>xve(t,e));async function J2(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function Ive(e,t){let n=await HJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await J2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);return i}async function Lve(e,t){let n=await HJ(e);if(!n)throw new E(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function Rve(e,t){let n=await HJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await J2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function zve(e,t){let n=await HJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await J2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);let a=await e1(e,t,i.clientId);if(!a)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,c=s.scopes;if(c&&!c.every(e=>o?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let l=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:/* @__PURE__ */ new Date(l*1e3)}})}const Bve=e=>X(`/oauth2/get-consent`,{method:`GET`,query:A({id:k()}),use:[WJ],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>Ive(t,e)),Vve=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[WJ],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Lve(t,e)),Hve=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[WJ],body:A({id:k(),update:A({scopes:Be(k())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>zve(t,e)),Uve=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[WJ],body:A({id:k()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>Rve(t,e)),Y2=e=>e.schema?.oauthResource?.modelName??`oauthResource`,X2=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,Wve=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function Z2(e){try{return decodeURIComponent(e)}catch{return e}}function Gve(e,t){return{identifier:e.identifier,name:e.name??e.identifier,accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}async function Kve(e,t){await p2(e,await HJ(e),t,`create`);let n=e.body;if(!n?.identifier)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await Cge(t,n.identifier);let r=/* @__PURE__ */ new Date,i;try{i=await e.context.adapter.create({model:Y2(t),data:Gve(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return X1(i.identifier),e.json(i,{status:201})}async function qve(e,t){await p2(e,await HJ(e),t,`list`);let n=await e.context.adapter.findMany({model:Y2(t)});return e.json(n??[])}async function Jve(e,t){let n=Z2(e.params.identifier);await p2(e,await HJ(e),t,`read`,n);let r=await e.context.adapter.findOne({model:Y2(t),where:[{field:`identifier`,value:n}]});if(!r)throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function Yve(e,t){let n=Z2(e.params.identifier);if(await p2(e,await HJ(e),t,`update`,n),!await e.context.adapter.findOne({model:Y2(t),where:[{field:`identifier`,value:n}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});let r={updatedAt:/* @__PURE__ */ new Date};for(let t of[`name`,`accessTokenTtl`,`refreshTokenTtl`,`signingAlgorithm`,`signingKeyId`,`allowedScopes`,`customClaims`,`dpopBoundAccessTokensRequired`,`disabled`,`metadata`])Object.prototype.hasOwnProperty.call(e.body,t)&&(r[t]=e.body[t]);await e.context.adapter.update({model:Y2(t),where:[{field:`identifier`,value:n}],update:r}),X1(n);let i=await e.context.adapter.findOne({model:Y2(t),where:[{field:`identifier`,value:n}]});if(!i)throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function Xve(e,t){let n=Z2(e.params.identifier);if(await p2(e,await HJ(e),t,`delete`,n),!await e.context.adapter.findOne({model:Y2(t),where:[{field:`identifier`,value:n}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:Y2(t),where:[{field:`identifier`,value:n}]}),X1(n),e.json({deleted:!0})}async function Zve(e,t){let n=await HJ(e),r=Z2(e.params.identifier),i=Z2(e.params.client_id);if(await p2(e,n,t,`link`,r),!await e.context.adapter.findOne({model:Y2(t),where:[{field:`identifier`,value:r}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:Wve(t),where:[{field:`clientId`,value:i}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:X2(t),data:{clientId:i,resourceId:r,createdAt:/* @__PURE__ */ new Date}})}catch(t){let n=t instanceof Error?t.message:String(t);if(/unique|duplicate|UNIQUE/i.test(n))return e.json({linked:!0,alreadyLinked:!0});throw t}return e.json({linked:!0})}async function Qve(e,t){let n=await HJ(e),r=Z2(e.params.identifier),i=Z2(e.params.client_id);return await p2(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:X2(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}const Q2=A({identifier:k().min(1).optional(),name:k().optional(),accessTokenTtl:Le().int().positive().nullable().optional(),refreshTokenTtl:Le().int().positive().nullable().optional(),signingAlgorithm:Ze(W1).nullable().optional(),signingKeyId:k().nullable().optional(),allowedScopes:Be(k()).nullable().optional(),customClaims:ze(k(),rt()).nullable().optional(),dpopBoundAccessTokensRequired:Je().optional(),disabled:Je().optional(),metadata:ze(k(),rt()).nullable().optional()}),$ve=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:Q2.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>Kve(t,e)),eye=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>qve(t,e)),tye=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Jve(t,e)),nye=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:Q2,metadata:{SERVER_ONLY:!0}},async t=>Yve(t,e)),rye=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Xve(t,e)),iye=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>Zve(t,e)),aye=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Qve(t,e));async function oye(e,t,n){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let r=K$(e.context),i=r.options,a;try{a=(await $F(n,cI(await FZ(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r.endpoints.getJwks(e))?.response,jwksCacheKey:r})),{issuer:i?.jwt?.issuer??e.context.baseURL})).payload}catch(e){if(e instanceof eP||e instanceof oP)return null;throw e instanceof TypeError||q$(e)?new O(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`}):e}let o=`${e.context.baseURL}/oauth2/userinfo`;if(!a.azp||!await K1(e,t,a.aud,[o]))return null;throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function sye(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await o1(t.storeTokens,i,`access_token`)}]});if(!a)throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`});if(!a.clientId||a.clientId!==r)return null;a.id?await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`id`,value:a.id}]}):await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`token`,value:a.token}]})}async function cye(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await o1(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`});if(i.revoked)throw await u0(e,r,i.userId),new O(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});if(!i.clientId||i.clientId!==r)return null;let a=Math.floor(Date.now()/1e3);if(!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:i.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:{revoked:/* @__PURE__ */ new Date(a*1e3)}}))throw await u0(e,r,i.userId),new O(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,value:i.id}]})}async function lye(e,t,n,r){try{return await oye(e,t,r)}catch(e){if(e instanceof O){if(e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}try{return await sye(e,t,r,n)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw new O(`BAD_REQUEST`,{error_description:`Invalid access token`,error:`invalid_request`})}async function uye(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new O(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=oZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await p1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await lye(e,t,c.clientId,n)}catch(e){if(e instanceof O){if(r===`access_token`||e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return await cye(e,t,(await l0(t,n)).token,c.clientId)}catch(e){if(e instanceof O){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof O){if(e.body?.error===`unsupported_token_type`)throw e;if(e.name===`BAD_REQUEST`)return null;throw e}throw e instanceof Error?(C.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(C.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}const dye={oauthClient:{modelName:`oauthClient`,fields:{clientId:{type:`string`,unique:!0,required:!0},clientSecret:{type:`string`,required:!1},clientDiscoveryId:{type:`string`,required:!1},disabled:{type:`boolean`,defaultValue:!1,required:!1},skipConsent:{type:`boolean`,required:!1},enableEndSession:{type:`boolean`,required:!1},subjectType:{type:`string`,required:!1},scopes:{type:`string[]`,required:!1},clientCredentialsScopes:{type:`string[]`,required:!1,defaultValue:[]},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},name:{type:`string`,required:!1},uri:{type:`string`,required:!1},icon:{type:`string`,required:!1},contacts:{type:`string[]`,required:!1},tos:{type:`string`,required:!1},policy:{type:`string`,required:!1},softwareId:{type:`string`,required:!1},softwareVersion:{type:`string`,required:!1},softwareStatement:{type:`string`,required:!1},redirectUris:{type:`string[]`,required:!0},postLogoutRedirectUris:{type:`string[]`,required:!1},backchannelLogoutUri:{type:`string`,required:!1},backchannelLogoutSessionRequired:{type:`boolean`,required:!1},tokenEndpointAuthMethod:{type:`string`,required:!1},applicationType:{type:`string`,required:!1},jwks:{type:`string`,required:!1},jwksUri:{type:`string`,required:!1},grantTypes:{type:`string[]`,required:!1},responseTypes:{type:`string[]`,required:!1},requirePKCE:{type:`boolean`,required:!1},dpopBoundAccessTokens:{type:`boolean`,required:!1,defaultValue:!1},referenceId:{type:`string`,required:!1},metadata:{type:`json`,required:!1}}},oauthResource:{modelName:`oauthResource`,fields:{identifier:{type:`string`,required:!0,unique:!0},name:{type:`string`,required:!0},accessTokenTtl:{type:`number`,required:!1},refreshTokenTtl:{type:`number`,required:!1},signingAlgorithm:{type:`string`,required:!1},signingKeyId:{type:`string`,required:!1},allowedScopes:{type:`string[]`,required:!1},customClaims:{type:`json`,required:!1},dpopBoundAccessTokensRequired:{type:`boolean`,required:!1,defaultValue:!1},disabled:{type:`boolean`,required:!1,defaultValue:!1},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},policyVersion:{type:`number`,required:!1,defaultValue:1},metadata:{type:`json`,required:!1}}},oauthClientResource:{modelName:`oauthClientResource`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`,onDelete:`cascade`},index:!0},resourceId:{type:`string`,required:!0,references:{model:`oauthResource`,field:`identifier`,onDelete:`cascade`},index:!0},metadata:{type:`json`,required:!1},createdAt:{type:`date`,required:!1}},indexes:[{fields:[`clientId`,`resourceId`],unique:!0}]},oauthRefreshToken:{fields:{token:{type:`string`,required:!0,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!0,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},rotatedAt:{type:`date`,required:!1},rotationReplayResponse:{type:`string`,required:!1},rotationReplayExpiresAt:{type:`date`,required:!1},authTime:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthAccessToken:{modelName:`oauthAccessToken`,fields:{token:{type:`string`,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},refreshId:{type:`string`,required:!1,references:{model:`oauthRefreshToken`,field:`id`},index:!0},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthConsent:{modelName:`oauthConsent`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},scopes:{type:`string[]`,required:!0},createdAt:{type:`date`},updatedAt:{type:`date`}}},oauthClientAssertion:{modelName:`oauthClientAssertion`,fields:{expiresAt:{type:`date`,required:!0}}}},$2=[`openid`,`profile`,`email`,`offline_access`],e4=A({id_token_hint:k().optional(),client_id:k().optional(),post_logout_redirect_uri:O1.optional(),state:k().optional()}),t4=SH(()=>null),n4=t4.get,r4=/* @__PURE__ */ new WeakMap,i4=`signedQueryIssuedAtMs`;function fye(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):void 0;if(!(!t||!Number.isFinite(t)||t<=0))return new Date(t)}const a4=e=>{let t=e.clientRegistrationAllowedScopes;if(e.clientRegistrationDefaultScopes){let n=t?/* @__PURE__ */ new Set([...t,...e.clientRegistrationDefaultScopes]):/* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes]);t=Array.from(n)}let n=new Set((e.scopes??$2).filter(e=>e.length));if(t){for(let e of t)if(!n.has(e))throw new D(`clientRegistrationAllowedScope ${e} not found in scopes`)}for(let t of e.advertisedMetadata?.scopes_supported??[])if(!n?.has(t))throw new D(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let r=new Set((e.resources??[]).map(e=>typeof e==`string`?e:e.identifier));for(let[t,n]of[[`clientRegistrationDefaultResources`,e.clientRegistrationDefaultResources],[`clientRegistrationAllowedResources`,e.clientRegistrationAllowedResources]])for(let e of n??[])if(!r.has(e))throw new D(`${t} resource ${e} not found in resources`);let i=/* @__PURE__ */ new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...L1.filter(e=>n.has(I1[e].scope))]),a={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:e.disableJwtPlugin?`encrypted`:`hashed`,storeTokens:`hashed`,grantTypes:[`authorization_code`,`client_credentials`,`refresh_token`],...e,scopes:Array.from(n),claims:Array.from(i),clientRegistrationAllowedScopes:t};if(L$(a.extensions),a.pairwiseSecret&&a.pairwiseSecret.length<32)throw new D(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(a.grantTypes&&a.grantTypes.includes(`refresh_token`)&&!a.grantTypes.includes(`authorization_code`))throw new D(`refresh_token grant requires authorization_code grant`);if(a.disableJwtPlugin&&(a.storeClientSecret===`hashed`||typeof a.storeClientSecret==`object`&&`hash`in a.storeClientSecret))throw new D(`unable to store hashed secrets because id tokens will be signed with secret`);if(!a.disableJwtPlugin&&(a.storeClientSecret===`encrypted`||typeof a.storeClientSecret==`object`&&(`encrypt`in a.storeClientSecret||`decrypt`in a.storeClientSecret)))throw new D(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let o=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=a.disableJwtPlugin?t.baseURL:K$(t)?.options?.jwt?.issuer??t.baseURL,o=`/`;try{o=new URL(i).pathname.replace(/\/$/,``)||``}catch{o=new URL(t.baseURL).pathname.replace(/\/$/,``)||``}let s={context:t},c=/* @__PURE__ */ new Set([`/.well-known/oauth-authorization-server${o}`,`${o}/.well-known/oauth-authorization-server`]),l=`${o}/.well-known/openid-configuration`,u=c.has(r),d=a.scopes?.includes(`openid`)&&r===l,f=t=>{let n=e2(t);return e.method===`HEAD`?new Response(null,{status:n.status,headers:n.headers}):n};if((u||d)&&e.method!==`GET`&&e.method!==`HEAD`)return{response:new Response(null,{status:405,headers:{Allow:`GET, HEAD`}})};if(u)return a.scopes?.includes(`openid`)?{response:f($0(s,a))}:{response:f(Q0(s,a))};if(d)return{response:f($0(s,a))}},s=t2(`/oauth2/authorize`,{method:[`GET`,`POST`],body:A({}).passthrough(),redirectOnError:g4(a),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body`,parameters:[{name:`response_type`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 response type (e.g., 'code')`},{name:`client_id`,in:`query`,required:!0,schema:{type:`string`},description:`OAuth 2.1 client ID`},{name:`redirect_uri`,in:`query`,required:!1,schema:{type:`string`,format:`uri`},description:`OAuth 2.1 redirect URI`},{name:`scope`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 scopes (space-separated)`},{name:`state`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 state parameter`},{name:`request_uri`,in:`query`,required:!1,schema:{type:`string`},description:`Pushed Authorization Request URI referencing stored parameters`},{name:`code_challenge`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge`},{name:`code_challenge_method`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge method`},{name:`nonce`,in:`query`,required:!1,schema:{type:`string`},description:`OpenID Connect nonce`},{name:`max_age`,in:`query`,required:!1,schema:{type:`integer`,minimum:0},description:`Maximum authentication age in seconds; forces re-authentication when exceeded`},{name:`resource`,in:`query`,required:!1,schema:{type:`array`,items:{type:`string`}},description:`Requested protected resource(s) for the access token. May be supplied multiple times as repeated 'resource' query parameters (RFC 8707) or as an array of strings.`},{name:`prompt`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth2 prompt parameter`}],responses:{302:{description:`Redirect to client with code or error`,headers:{Location:{description:`Redirect URI with code or error`,schema:{type:`string`,format:`uri`}}}},400:{description:`Invalid request`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},state:{type:`string`}},required:[`error`]}}}}}}}},async e=>bye(e,a,e.authorizeSettings??{isAuthorize:!0})),c=(e,t)=>bQ(s,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:`1.7.12`,options:a,onRequest:o,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new D("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(a.allowClientKeyRotation){let t=e.adapter.id===`memory`?`the memory adapter`:e.options.advanced?.database?.generateId===`serial`?'`advanced.database.generateId: "serial"`':void 0;if(t)throw new D(`\`allowClientKeyRotation\` requires single-use client assertions, which ${t} does not enforce`)}if(await e0(e,a).catch(t=>Pge(e,t)),Lge(a),!a.disableJwtPlugin){let t=K$(e)?.options,n=t?.jwt?.issuer??e.baseURL,r=t?.jwt?.issuer==null&&typeof e.options.baseURL==`object`&&e.options.baseURL!==null&&`allowedHosts`in e.options.baseURL;try{new URL(n)}catch(e){if(!r||n!==``)throw e}}return{options:{databaseHooks:{session:{delete:{async before(e,t){if(!t)return;let n=await D_e(t,a,{sessionId:e.id,userId:e.userId});if(!n)return;let r=r4.get(t)??/* @__PURE__ */ new Map;r.set(e.id,n),r4.set(t,r)},async after(e,t){if(!t)return;let n=r4.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&r4.delete(t),!r)return;let i=O_e(t,r).catch(e=>{t.context.logger.error(`Back-channel logout failed after session deletion`,e)});await t.context.runInBackgroundOrAwait(i)}}}}}}},hooks:{before:[{matcher(e){return e.body?.oauth_query},handler:Hq(async e=>{let t=e.body.oauth_query;if(!await Q$(t,e.context.secret))throw new E(`BAD_REQUEST`,{error:`invalid_signature`});let n=Ehe(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(k$),r.delete(A$),await t4.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Nq({query:r.toString(),...n?{[i4]:n.getTime()}:{}})})}],after:[{matcher(e){return wG(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:Hq(async e=>{let t=wG(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await t4.get(),r=(await Aq())?.serverContext,i=n?.query??r?.query;if(!i)return;let a=new URLSearchParams(i),o=await e.context.internalAdapter.findSession(t);if(!o)return;e.context.session=o;let s=e.request?.headers?.get(`sec-fetch-mode`)?.toLowerCase(),l=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(l.includes(`text/html`)||l.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let u=n?.signedQueryIssuedAt??fye(r?.[i4]),d=C1(a,`login`);return S1(o.session.createdAt,u)&&(d=w1(d)),e.query=x1(d),await c(e)})}]},endpoints:{getOAuthServerConfig:X(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>a.scopes&&a.scopes.includes(`openid`)?$0(e,a):Q0(e,a)),getOpenIdConfig:X(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(a.scopes&&!a.scopes.includes(`openid`))throw new E(`NOT_FOUND`);return $0(e,a)}),oauth2Authorize:s,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:A({accept:Je().meta({description:`Accept or deny user consent for a set of scopes`}),scope:k().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:N1.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),oauth_query:k().optional().meta({description:`The redirected page's query parameters`})}),use:[WJ],metadata:{openapi:{description:`Handle OAuth2 consent`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect:{type:`boolean`,description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:`string`,format:`uri-reference`,description:`The absolute or relative URI to redirect to next.`}},required:[`redirect`,`url`]}}}}}}}},async e=>x_e(e,a,c)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:A({selected:Je().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:Je().optional().meta({description:`Confirms an account was registered`}),postLogin:Je().optional().meta({description:`Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true.`}),oauth_query:k().optional().meta({description:`The redirected page's query parameters`})}),use:[WJ],metadata:{openapi:{description:`Continues OAuth2 authorization flow`,responses:{200:{description:`Authorization flow continued successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect:{type:`boolean`,description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:`string`,format:`uri-reference`,description:`The absolute or relative URI to redirect to next.`}},required:[`redirect`,`url`]}}}}}}}},async e=>S_e(e,c)),oauth2Token:t2(`/oauth2/token`,{method:`POST`,cloneRequest:!0,body:A({grant_type:k().trim().min(1),client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),code:k().optional(),code_verifier:k().optional(),redirect_uri:O1.optional(),refresh_token:k().optional(),resource:Ae([B1,Be(B1).min(1)]).optional(),scope:k().optional()}).passthrough(),errorCodesByField:{grant_type:{missing:`invalid_request`,invalid:`unsupported_grant_type`},resource:{invalid:`invalid_target`}},metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Obtain an OAuth2.1 access token`,parameters:[{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens`}],requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{grant_type:{type:`string`,description:`OAuth2 grant type`},client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},code:{type:`string`,description:`Authorization code (for authorization_code grant)`},code_verifier:{type:`string`,description:`PKCE code verifier (for authorization_code grant)`},redirect_uri:{type:`string`,format:`uri`,description:`Redirect URI (for authorization_code grant)`},refresh_token:{type:`string`,description:`Refresh token (for refresh_token grant)`},resource:{oneOf:[{type:`string`,description:`Single resource (URL)`},{type:`array`,items:{type:`string`},description:`Multiple resources (URLs)`}],description:`Requested protected resource(s) for the access token`},scope:{type:`string`,description:`Requested scopes (for client_credentials grant)`}},required:[`grant_type`]}}}},responses:{200:{description:`Access token response`,content:{"application/json":{schema:{type:`object`,properties:{access_token:{type:`string`,description:`The access token issued by the authorization server`},token_type:{type:`string`,description:`The type of the token issued`,enum:[`Bearer`,`DPoP`]},expires_in:{type:`number`,description:`Lifetime in seconds of the access token`},refresh_token:{type:`string`,description:`Refresh token, if issued`},scope:{type:`string`,description:`Scopes granted by the access token`},id_token:{type:`string`,description:`ID Token (if OpenID Connect)`}},required:[`access_token`,`token_type`,`expires_in`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>{if(e.request){let t=await Tge(e.request);t&&t.length>1&&(e.body.resource=t)}return Uge(e,a)}),oauth2Introspect:t2(`/oauth2/introspect`,{method:`POST`,cloneRequest:!0,body:A({client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),token:k(),token_type_hint:k().optional()}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Introspect an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to introspect (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token introspection response`,content:{"application/json":{schema:{type:`object`,properties:{active:{type:`boolean`,description:`Whether the token is active`},scope:{type:`string`,description:`Scopes associated with the token`},client_id:{type:`string`,description:`Client ID associated with the token`},username:{type:`string`,description:`Username associated with the token`},token_type:{type:`string`,description:`Type of the token`},exp:{type:`number`,description:`Expiration time of the token (seconds since epoch)`},iat:{type:`number`,description:`Issued at time (seconds since epoch)`},nbf:{type:`number`,description:`Not before time (seconds since epoch)`},sub:{type:`string`,description:`Subject of the token`},aud:{type:`string`,description:`Audience of the token`},iss:{type:`string`,description:`Issuer of the token`},jti:{type:`string`,description:`JWT ID`}},required:[`active`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>A0(e,a)),oauth2Revoke:t2(`/oauth2/revoke`,{method:`POST`,cloneRequest:!0,body:A({client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),token:k(),token_type_hint:k().optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Revoke an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to revoke (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token revoked successfully. The response body is empty.`,content:{"application/json":{schema:{type:`object`,description:`Empty object on success`}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>uye(e,a)),oauth2UserInfo:X(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:A({access_token:k().optional()}).passthrough().optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Get OpenID Connect user information (UserInfo endpoint)`,security:[{bearerAuth:[]},{OAuth2:[`openid`,`profile`,`email`]}],parameters:[{name:`Authorization`,in:`header`,required:!1,schema:{type:`string`},description:`Bearer or DPoP access token`},{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT when using a DPoP-bound access token`}],responses:{200:{description:`User information retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{sub:{type:`string`,description:`Subject identifier (user ID)`},email:{type:`string`,format:`email`,nullable:!0,description:`User's email address, included if 'email' scope is granted`},name:{type:`string`,nullable:!0,description:`User's full name, included if 'profile' scope is granted`},picture:{type:`string`,format:`uri`,nullable:!0,description:`User's profile picture URL, included if 'profile' scope is granted`},given_name:{type:`string`,nullable:!0,description:`User's given name, included if 'profile' scope is granted`},family_name:{type:`string`,nullable:!0,description:`User's family name, included if 'profile' scope is granted`},email_verified:{type:`boolean`,nullable:!0,description:`Whether the email is verified, included if 'email' scope is granted`}},required:[`sub`]}}}},401:{description:`Unauthorized - invalid or missing access token`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}},403:{description:`Forbidden - insufficient scope`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}}}}}},async e=>Vge(e,a)),oauth2EndSession:t2(`/oauth2/end-session`,{method:[`GET`,`POST`],body:e4.optional(),query:e4.optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},query:{}},openapi:{description:`RP-Initiated Logout endpoint. Accepts standard logout parameters through GET or an application/x-www-form-urlencoded POST body, plus JSON for Better Auth generated-client calls. Requests without a usable id_token_hint may require explicit OP confirmation.`,responses:{200:{description:`Logout completed, or an HTML confirmation page was returned for browser navigation. A redirect is used only for an exact registered post_logout_redirect_uri.`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`URI to redirect to after logout (if post_logout_redirect_uri was provided)`},message:{type:`string`,description:`Success message`}}}},"text/html":{schema:{type:`string`}}}}}}}},async e=>z_e(e,a)),oauth2EndSessionConfirmation:t2(`/oauth2/end-session/confirm`,{method:`POST`,body:A({action:Ye(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>B_e(e,a)),registerOAuthClient:t2(`/oauth2/register`,{method:`POST`,body:U1,errorCodesByField:{redirect_uris:`invalid_redirect_uri`,post_logout_redirect_uris:`invalid_redirect_uri`,software_statement:`invalid_software_statement`,resources:`invalid_target`},defaultError:`invalid_client_metadata`,metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`Name of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URL for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},post_logout_redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed logout redirect uris`},backchannel_logout_uri:{type:`string`,format:`uri`,description:`RP URL to receive signed Logout Tokens when the end-user's OP session terminates`},backchannel_logout_session_required:{type:`boolean`,description:"Whether the RP requires a `sid` claim in every Logout Token"},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final resource identifiers linked to the registered client`},disabled:{type:`boolean`,description:`Whether the client is disabled`}},required:[`client_id`]}}}}}}}},async e=>hve(e,a)),adminCreateOAuthClient:Tve(a),createOAuthClient:Eve(a),getOAuthClient:Dve(a),getOAuthClientPublic:Ove(a),getOAuthClientPublicPrelogin:kve(a),getOAuthClients:Ave(a),adminUpdateOAuthClient:jve(a),updateOAuthClient:Mve(a),rotateClientSecret:Nve(a),rotateClientKeys:Pve(a),deleteOAuthClient:Fve(a),getOAuthConsent:Bve(a),getOAuthConsents:Vve(a),updateOAuthConsent:Hve(a),deleteOAuthConsent:Uve(a),adminCreateOAuthResource:$ve(a),adminListOAuthResources:eye(a),adminGetOAuthResource:tye(a),adminUpdateOAuthResource:nye(a),adminDeleteOAuthResource:rye(a),adminLinkClientResource:iye(a),adminUnlinkClientResource:aye(a)},schema:fG(structuredClone(dye),a?.schema),rateLimit:[...a.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:a.rateLimit?.token?.window??60,max:a.rateLimit?.token?.max??20}],...a.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:a.rateLimit?.authorize?.window??60,max:a.rateLimit?.authorize?.max??30}],...a.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:a.rateLimit?.introspect?.window??60,max:a.rateLimit?.introspect?.max??100}],...a.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:a.rateLimit?.revoke?.window??60,max:a.rateLimit?.revoke?.max??30}],...a.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:a.rateLimit?.register?.window??60,max:a.rateLimit?.register?.max??5}],...a.rateLimit?.rotateClientKeys===!1?[]:[{pathMatcher:e=>e===`/oauth2/client/rotate-keys`,window:a.rateLimit?.rotateClientKeys?.window??60,max:a.rateLimit?.rotateClientKeys?.max??5}],...a.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:a.rateLimit?.userinfo?.window??60,max:a.rateLimit?.userinfo?.max??60}]]}};function pye(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function mye(e){let{max_age:t,...n}=e;return n}function o4(e,t,n,r,i,a=`query`){let o=new URLSearchParams({error:t,error_description:n});return r&&o.append(`state`,r),i&&o.append(`iss`,i),a===`fragment`?`${e}#${o.toString()}`:Cq(e,o)}function hye(e){let t=typeof e.response_mode==`string`?e.response_mode:void 0;if(t===`fragment`)return`fragment`;if(t===`query`)return`query`;let n=typeof e.response_type==`string`?e.response_type:void 0;return n&&/\b(token|id_token)\b/.test(n)?`fragment`:`query`}const gye={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function _ye(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function s4(e){return typeof e==`string`?e:void 0}function vye(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{..._ye(n)?n:{}}}const c4=(e,t)=>{let n=j0(e.request?.headers),r=e.headers?.get(`accept`)?.includes(`application/json`);if(n||r)return{redirect:!0,url:t.toString()};throw e.redirect(t)};function l4(e,t,n,r,i){return c4(e,o4(n.redirect_uri,r,i,n.state,d4(e,t)))}function u4(e){try{let t=new URL(e);return t.protocol!==`https:`&&!SY(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function d4(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=K$(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return u4(n)}function f4(e,t,n){return o4(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function p4(e){let t;try{t=new URL(e)}catch{return}let n=xY(t.hostname)||t.hostname===`localhost`;if(t.protocol!==`http:`||!n)return;let r=e.indexOf(`://`);if(r<0)return;let i=r+3,a=e.slice(i).search(/[/?#]/u),o=e.length;a>=0&&(o=i+a);let s=e.slice(i,o),c;if(s.startsWith(`[`)){let t=s.indexOf(`]`);if(t<0)return;if(s[t+1]!==`:`)return e;c=t+1}else if(c=s.lastIndexOf(`:`),c<0)return e;let l=s.slice(c+1);if(!/^\d*$/u.test(l))return;let u=i+c;return`${e.slice(0,u)}${e.slice(o)}`}function m4(e,t){if(!e||!t)return;let n;try{n=new URL(t)}catch{return}let r=t.includes(`#`),i=n.username.length>0||n.password.length>0;if(r||i)return;let a=p4(t);return e.find(e=>e===t?!0:a?p4(e)===a:!1)}function h4(e){if(!O1.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function yye(e,t,n,r){if(!n||!r)return null;let i;try{i=await e1(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=m4(a,r);if(t.validateRedirectUri){if(!h4(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function g4(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await yye(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?c4(r,o4(a,t,n,typeof i.state==`string`?i.state:void 0,d4(r,e),hye(i))):c4(r,f4(r,t,n))}}async function bye(e,t,n){if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new O(`NOT_FOUND`);if(!e.request)throw new O(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=vye(e,n);e.query=i;let a=s4(i.request),o=s4(i.request_uri);if(a!==void 0&&o!==void 0)return g4(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return g4(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=s4(i.client_id);if(!n)return g4(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return g4(t)({error:`request_uri_not_supported`,error_description:`request_uri not supported`,ctx:e});let r=await t.requestUriResolver({requestUri:o,clientId:n,ctx:e});if(!r)return g4(t)({error:`invalid_request_uri`,error_description:`request_uri is invalid or expired`,ctx:e});let a=i.client_id;i=r,a&&(i.client_id=a)}e.query=i;let s=H1.safeParse(i);if(!s.success){let n=n2(s.error.issues,gye);return g4(t)({...n,ctx:e})}if(i=s.data,e.query=i,await t4.set({query:_4(i).toString()}),!i.response_type)return g4(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?_1(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return c4(e,f4(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return c4(e,f4(e,`unsupported_response_type`,`unsupported response type`));let u=await e1(e,t,i.client_id);if(!u)return c4(e,f4(e,`invalid_client`,`client not found`));if(u.disabled)return c4(e,f4(e,`client_disabled`,`client is disabled`));if(!u1(u,`authorization_code`))return c4(e,f4(e,`unauthorized_client`,`client is not authorized to use the authorization_code grant`));let d=u.redirectUris??[],f=!1;if(i.redirect_uri){let e=!!m4(d,i.redirect_uri);if(t.validateRedirectUri&&h4(i.redirect_uri))try{f=await t.validateRedirectUri(i.redirect_uri,d,e)}catch{f=!1}else t.validateRedirectUri||(f=e)}if(!f)return c4(e,f4(e,`invalid_redirect`,`invalid redirect uri`));let p=i.scope?.split(` `).filter(e=>e);if(p){let n=new Set(u.scopes??t.scopes),r=p.filter(e=>!n?.has(e));if(r.length)return c4(e,o4(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,d4(e,t)))}p||(p=u.scopes??t.scopes??[],i.scope=p.join(` `));let m=p.includes(`openid`);if(i.claims!==void 0&&!m)return c4(e,o4(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,d4(e,t)));if(m&&!lge(i.claims))return c4(e,o4(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,d4(e,t)));if(m&&!uge(i.claims,`0`))return c4(e,o4(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,d4(e,t)));let h=P1(i.claims,R1(t));if(i.resource!==void 0)try{await q1(e,t,{resource:i.resource,clientId:u.clientId,requestedScopes:p})}catch(n){if(n instanceof O){let r=n.body?.error??`invalid_target`,a=n.body?.error_description??`requested resource invalid`;return c4(e,o4(i.redirect_uri,r,a,i.state,d4(e,t)))}throw n}let g=T1(u,{scopes:p,nonce:i.nonce});if(g&&(!i.code_challenge||!i.code_challenge_method))return c4(e,o4(i.redirect_uri,`invalid_request`,g.valueOf(),i.state,d4(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return c4(e,o4(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,d4(e,t)));if(![`S256`].includes(i.code_challenge_method))return c4(e,o4(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,d4(e,t)))}let _=Y$(i.resource)??[],v=await HJ(e),y=i.max_age,b=v!=null&&y!==void 0&&pye(new Date(v.session.createdAt),y,/* @__PURE__ */ new Date);if(!v||v!=null&&y!==void 0&&!b||c?.has(`login`)||c?.has(`create`))return l?l4(e,t,i,`login_required`,`authentication required`):y4(e,t,c?.has(`create`)?`create`:`login`);if(b&&(i=mye(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return y4(e,t,`select_account`);if(n?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p}))return l?l4(e,t,i,`account_selection_required`,`End-User account selection is required`):y4(e,t,`select_account`);if(t.signup?.shouldRedirect){let n=await t.signup.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p});if(n)return l?l4(e,t,i,`interaction_required`,`End-User interaction is required`):y4(e,t,`create`,{page:typeof n==`string`?n:void 0})}if(!n?.postLogin&&t.postLogin&&await t.postLogin.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p,isContinuation:n?.isPostLoginContinuation??!1}))return l?l4(e,t,i,`interaction_required`,`End-User interaction is required`):y4(e,t,`post_login`);if(c?.has(`consent`))return y4(e,t,`consent`,{sessionId:v.session.id});let x=await y1(t,{user:v.user,session:v.session,scopes:p});if(u.skipConsent)return v4(e,t,{query:i,clientId:u.clientId,userId:v.user.id,sessionId:v.session.id,authTime:new Date(v.session.createdAt).getTime(),referenceId:x,resource:_});let S=await b1(e,u.clientId,v.user.id,x);if(!S||!p.every(e=>S.scopes.includes(e))||!h.every(e=>(S.requestedUserInfoClaims??[]).includes(e)))return l?l4(e,t,i,`consent_required`,`End-User consent is required`):y4(e,t,`consent`,{sessionId:v.session.id});let ee=S?.resources??[];return _.some(e=>!ee.includes(e))?l?l4(e,t,i,`consent_required`,`End-User consent is required`):y4(e,t,`consent`,{sessionId:v.session.id}):v4(e,t,{query:i,clientId:u.clientId,userId:v.user.id,sessionId:v.session.id,authTime:new Date(v.session.createdAt).getTime(),referenceId:x,resource:_})}function _4(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else n===`claims`&&typeof r==`object`?t.set(n,JSON.stringify(r)):t.set(n,String(r))}return t}async function v4(e,t,n){let r=ZH(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await a1(t.storeTokens,r,`authorization_code`),updatedAt:/* @__PURE__ */ new Date(i*1e3),expiresAt:/* @__PURE__ */ new Date(a*1e3),value:JSON.stringify({type:`authorization_code`,query:n.query,userId:n.userId,sessionId:n?.sessionId,referenceId:n.referenceId,authTime:n.authTime,resource:n.resource})};await e.context.internalAdapter.createVerificationValue({...o,createdAt:/* @__PURE__ */ new Date(i*1e3)});let s=new URL(n.query.redirect_uri);return s.searchParams.set(`code`,r),n.query.state&&s.searchParams.set(`state`,n.query.state),s.searchParams.set(`iss`,d4(e,t)),c4(e,s.toString())}async function y4(e,t,n,r){let i=await xye(e,t,{postLoginClearedForSession:n===`consent`&&t.postLogin?r?.sessionId:void 0}),a=t.loginPage;if(n===`select_account`)a=t.selectAccount?.page??t.loginPage;else if(n===`post_login`){if(!t.postLogin?.page)throw new O(`INTERNAL_SERVER_ERROR`,{error_description:`postLogin should have been defined`});a=t.postLogin?.page}else n===`consent`?a=t.consentPage:n===`create`&&(a=t.signup?.page??t.loginPage);return c4(e,`${r?.page??a}?${i}`)}async function xye(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=_4(e.query);a.set(`exp`,String(i)),a.set(k$,String(r)),a.delete(`sig`),a.delete(A$),n?.postLoginClearedForSession&&a.set(A$,n.postLoginClearedForSession),The(a);let o=await WW(M$(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}const Sye=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,Cye=/* @__PURE__ */ new Set([`client_secret_post`,`client_secret_basic`,`client_secret_jwt`]);function b4(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`}function wye(e){if(Sye.test(e))return`client_id URL MUST NOT contain dot segments`;if(e.includes(`#`))return`client_id URL MUST NOT contain a fragment`;let t;try{t=new URL(e)}catch{return`client_id is not a valid URL`}if(t.protocol!==`https:`)return`client_id URL must use HTTPS`;let n=/^https:\/\//i.exec(e);if(!n||e.includes(`\\`))return`client_id URL MUST use an explicit HTTPS authority form`;let r=e.slice(n[0].length),i=r.search(/[/?#]/);return i===0?`client_id URL MUST use an explicit HTTPS authority form`:i<0||r[i]!==`/`?`client_id URL MUST contain an explicit path component`:t.username||t.password?`client_id URL MUST NOT contain credentials`:CY(t.hostname)?null:`client_id URL must not target a private or reserved address`}function Tye(e){let t=[];try{let n=new URL(e);n.pathname===`/`&&t.push(`client_id URL path / is NOT RECOMMENDED (§3)`),n.search&&t.push(`client_id URL SHOULD NOT contain a query string (§3)`)}catch{}return t}function Eye(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||D1(t)}catch{return!1}}function Dye(e,t,n={}){if(!t||typeof t!=`object`)return{valid:!1,error:`metadata document is not a JSON object`};for(let e of Object.keys(t))if(u2(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let r=xge.strip().safeParse(t);if(!r.success){let e=r.error.issues[0];return{valid:!1,error:`${e?.path.join(`.`)||`metadata document`}: ${e?.message??`invalid client metadata`}`}}let i=r.data,a=[];if(i.client_id!==e)return{valid:!1,error:`client_id "${String(i.client_id)}" does not match the metadata document URL`};if(n.metadataProfile===`mcp-2026-07-28`&&!i.client_name?.trim())return{valid:!1,error:`client_name must be a non-empty string`};for(let e of[`backchannel_logout_uri`,`backchannel_logout_session_required`])if(i[e]!==void 0)return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let o=/* @__PURE__ */ new Set([`none`,`private_key_jwt`]);if(typeof i.token_endpoint_auth_method==`string`){if(Cye.has(i.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${i.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!o.has(i.token_endpoint_auth_method))return{valid:!1,error:`token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients`};if(i.token_endpoint_auth_method===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)return{valid:!1,error:`private_key_jwt requires either jwks or jwks_uri in the metadata document`}}if(i.jwks&&!c2(i.jwks).valid)return{valid:!1,error:`jwks must contain only structurally valid public keys`};if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.username||e.password)return{valid:!1,error:`jwks_uri must not contain credentials`};if(i.jwks_uri.includes(`#`))return{valid:!1,error:`jwks_uri must not contain a fragment`}}catch{return{valid:!1,error:`jwks_uri must be a valid URL`}}if(n.metadataProfile===`mcp-2026-07-28`&&!i.redirect_uris||i.redirect_uris&&!i.redirect_uris.every(e=>Eye(e)))return{valid:!1,error:`redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs`};for(let e of[`client_uri`,`logo_uri`,`tos_uri`,`policy_uri`]){if(i[e]!==void 0&&typeof i[e]!=`string`)return{valid:!1,error:`${e} must be a string`};if(typeof i[e]==`string`)try{let t=new URL(i[e]);if(t.protocol!==`https:`&&t.protocol!==`http:`)return{valid:!1,error:`${e} must use HTTP(S)`};if(t.username||t.password)return{valid:!1,error:`${e} must not contain credentials`};if(!CY(t.hostname))return{valid:!1,error:`${e} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${e} is not a valid URL`}}}let s=n.originBoundFields??[`post_logout_redirect_uris`,`client_uri`],c;try{c=new URL(e).origin}catch{return{valid:!1,error:`client_id is not a valid URL`}}for(let e of s){let t=i[e];if(t===void 0)continue;let n;if(typeof t==`string`)n=[t];else if(Array.isArray(t)){if(!t.every(e=>typeof e==`string`))return{valid:!1,error:`${e} must be a string or an array of strings`};n=t}else return{valid:!1,error:`${e} must be a string or an array of strings`};for(let t of n){let n;try{n=new URL(t)}catch{return{valid:!1,error:`${e} contains an invalid URL: "${t}"`}}let r=e===`redirect_uris`||e===`post_logout_redirect_uris`,i=r&&D1(n);if(n.protocol!==`https:`&&n.protocol!==`http:`&&!i)return{valid:!1,error:`all values for ${e} must use HTTP(S) or a private-use scheme`};if(i&&(e===`redirect_uris`||E1(n)))continue;let a=r&&(n.protocol===`http:`||n.protocol===`https:`)&&SY(n.hostname);if(n.origin!==c&&!a)return{valid:!1,error:`${e} value "${t}" must have the same origin as client_id (${c})`}}}return a.push(...Tye(e)),{valid:!0,metadata:{...i,token_endpoint_auth_method:i.token_endpoint_auth_method??`none`},...a.length>0?{warnings:a}:{}}}const x4=5e3,S4=5120,Oye=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,C4=`Failed to fetch metadata document (network error or redirect blocked)`,w4=`cimd`;function T4(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function E4(){return T4(`Metadata document exceeds ${S4/1024}KB size limit`)}async function kye(e,t,n){let r=e.body?.getReader();if(!r){let n=await e.text();if(new TextEncoder().encode(n).byteLength>t)throw E4();return n}let i=[],a=0,o,s=new Promise((e,t)=>{o=t}),c=()=>{o?.(/* @__PURE__ */ Error(`Metadata document body read aborted`)),r.cancel().catch(()=>{})};n.aborted?c():n.addEventListener(`abort`,c,{once:!0});try{for(;;){let{done:e,value:n}=await Promise.race([r.read(),s]);if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel(),E4();i.push(n)}}finally{n.removeEventListener(`abort`,c),r.releaseLock()}let l=new Uint8Array(a),u=0;for(let e of i)l.set(e,u),u+=e.byteLength;return new TextDecoder().decode(l)}function Aye(e){return{cacheControl:e.get(`cache-control`)??void 0,vary:e.get(`vary`)??void 0,expires:e.get(`expires`)??void 0,date:e.get(`date`)??void 0,age:e.get(`age`)??void 0,etag:e.get(`etag`)??void 0,lastModified:e.get(`last-modified`)??void 0}}async function jye(e,t,n,r){let i=wye(t);if(i)throw T4(i);if(n.isMetadataDocumentUrlAllowed&&!await n.isMetadataDocumentUrlAllowed(t,e))throw T4(`client_id URL is not permitted by the server's fetch policy`);let a=new Headers({Accept:`application/json`});r?.etag&&a.set(`If-None-Match`,r.etag),r?.lastModified&&a.set(`If-Modified-Since`,r.lastModified);let o,s=new AbortController,c=!1,l=setTimeout(()=>{c=!0,s.abort()},x4);try{try{o=await n.fetchClientMetadataResource(t,{headers:a,redirect:`error`,signal:s.signal})}catch{throw T4(c?`Metadata document fetch timed out after ${x4}ms`:C4)}if(o.redirected)throw T4(`Metadata document fetch must not follow redirects`);let i=Aye(o.headers);if(o.status===304){if(!r?.etag&&!r?.lastModified)throw T4(`Metadata document returned 304 without a conditional validator`);return{status:`not-modified`,cacheHeaders:i}}if(o.status!==200)throw T4(`Metadata document fetch returned HTTP ${o.status}`);let l=o.headers.get(`content-type`)??``;if(!Oye.test(l))throw T4(`Metadata document must be JSON (got Content-Type "${l||`(none)`}")`);let u;try{let e=o.headers.get(`content-length`);if(e){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>S4)throw await o.body?.cancel(),E4()}u=await kye(o,S4,s.signal)}catch(e){throw c?T4(`Metadata document fetch timed out after ${x4}ms`):e instanceof O?e:T4(C4)}let d;try{d=JSON.parse(u)}catch{throw T4(`Metadata document is not valid JSON`)}let f=Dye(t,d,{originBoundFields:n.originBoundFields,metadataProfile:n.metadataProfile});if(!f.valid)throw T4(f.error);for(let t of f.warnings??[])e.context.logger.warn(`cimd metadata document warning: ${t}`);return{status:`modified`,metadata:f.metadata,cacheHeaders:i}}finally{clearTimeout(l)}}async function D4(e,t,n,r,i,a){let o=a?{...a}:void 0,s=await z2(e,i,{clientId:t,clientDiscoveryId:w4,metadata:{...n,client_id:n.client_id,redirect_uris:n.redirect_uris??[]},existingClient:a});if(s.created)try{await r.onClientCreated?.({client:s.client,clientMetadataDocument:n,context:e})}catch(t){e.context.logger.error(`cimd onClientCreated notification failed`,t)}else try{o&&await r.onClientRefreshed?.({client:s.client,previousClient:o,clientMetadataDocument:n,context:e})}catch(t){e.context.logger.error(`cimd onClientRefreshed notification failed`,t)}return s.client}const O4={minimumFetchInterval:1,maximumConcurrentFetches:16,maximumConcurrentFetchesPerOrigin:4,maximumFetchesPerMinute:120,maximumFetchesPerOriginPerMinute:30};function Mye(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function k4(e){return new O(`TOO_MANY_REQUESTS`,{error:`temporarily_unavailable`,error_description:e})}function Nye(e,t){if(typeof e==`number`){if(!Number.isFinite(e)||e<0)throw new D(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`);return e*1e3}try{let t=Math.floor(Date.now()/1e3),n=(x$(e,t)-t)*1e3;if(!Number.isFinite(n)||n<0)throw Error(`negative duration`);return n}catch{throw new D(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`)}}function A4(e,t){if(!Number.isInteger(e)||e<1)throw new D(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function Pye(e){let t=e.metadataFetchPolicy;return{minimumFetchIntervalMs:Nye(t?.minimumFetchInterval??O4.minimumFetchInterval,`minimumFetchInterval`),maximumConcurrentFetches:A4(t?.maximumConcurrentFetches??O4.maximumConcurrentFetches,`maximumConcurrentFetches`),maximumConcurrentFetchesPerOrigin:A4(t?.maximumConcurrentFetchesPerOrigin??O4.maximumConcurrentFetchesPerOrigin,`maximumConcurrentFetchesPerOrigin`),maximumFetchesPerMinute:A4(t?.maximumFetchesPerMinute??O4.maximumFetchesPerMinute,`maximumFetchesPerMinute`),maximumFetchesPerOriginPerMinute:A4(t?.maximumFetchesPerOriginPerMinute??O4.maximumFetchesPerOriginPerMinute,`maximumFetchesPerOriginPerMinute`)}}function j4(e,t){let n=t-6e4,r=0;for(;r<e.length&&e[r]<=n;)r+=1;r>0&&e.splice(0,r)}function Fye(e,t){if(typeof e==`number`)return Math.max(0,e*1e3);let n=Math.floor(t/1e3);return Math.max(0,(x$(e,n)-n)*1e3)}function Iye(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;for(let r of e?.split(`,`)??[]){let[e,...i]=r.trim().split(`=`),a=e?.toLowerCase();if(!a)continue;t.has(a)&&n.add(a);let o=i.join(`=`).trim();t.set(a,!o||o.replace(/^"|"$/g,``))}return{directives:t,duplicates:n}}function M4(e){if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Lye(e,t,n){let{directives:r,duplicates:i}=Iye(e.cacheControl),a=e.vary?.split(`,`).some(e=>e.trim()===`*`);if(r.has(`no-store`)||r.has(`private`)||a)return{cacheable:!1,expiresAt:n};let o=Fye(t,n);if(r.has(`no-cache`))return{cacheable:!0,expiresAt:n};let s=M4(e.age)??0,c=e.date?Date.parse(e.date):n,l=Number.isFinite(c)?Math.max(0,n-c):0,u=Math.max(l,s*1e3),d=null,f=r.has(`s-maxage`),p=M4(r.get(`s-maxage`)),m=r.has(`max-age`),h=M4(r.get(`max-age`)),g=f?p===null||i.has(`s-maxage`):m&&(h===null||i.has(`max-age`)),_=f?p:h;if(g)d=0;else if(_!==null)d=Math.max(0,_*1e3-u);else if(e.expires){let t=Date.parse(e.expires);Number.isFinite(t)&&(d=Math.max(0,t-(Number.isFinite(c)?c:n)-u))}return{cacheable:!0,expiresAt:n+Math.min(o,d??o)}}function Rye(e,t){return{cacheControl:t.cacheControl??e.cacheControl,vary:t.vary??e.vary,expires:t.expires??e.expires,date:t.date??e.date,age:t.age??e.age,etag:t.etag??e.etag,lastModified:t.lastModified??e.lastModified}}function zye(e,t,n,r){let i=Lye(t,n,r);return i.cacheable?{metadata:e,expiresAt:i.expiresAt,etag:t.etag,lastModified:t.lastModified,responseCacheHeaders:t}:null}function Bye(e){let t=e.metadataRevalidationInterval??`60m`,n=e.maxCacheEntries??1e3;if(!Number.isInteger(n)||n<1)throw new D(`cimd maxCacheEntries must be a positive integer`);let r=Pye(e),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=[],l=0,u=e=>{let t=i.get(e);if(t)return i.delete(e),i.set(e,t),t},d=(e,t)=>{for(i.delete(e);i.size>=n;){let e=i.keys().next().value;if(typeof e!=`string`)break;i.delete(e)}i.set(e,t)},f=(e,t)=>{if(!o.has(e))for(;o.size>=n;){let e=!1;for(let[n,i]of o)if(!a.has(n)&&!(r.minimumFetchIntervalMs>0&&t-i<r.minimumFetchIntervalMs)){o.delete(n),e=!0;break}if(!e)throw k4(`metadata fetch client state is at capacity`)}},p=(e,t)=>{let r=s.get(e);if(r)return j4(r.fetchStartTimesMs,t),s.delete(e),s.set(e,r),r;for(;s.size>=n;){let e=!1;for(let[n,r]of s)if(j4(r.fetchStartTimesMs,t),!(r.activeFetchCount>0||r.fetchStartTimesMs.length>0)){s.delete(n),e=!0;break}if(!e)throw k4(`metadata fetch origin state is at capacity`)}let i={activeFetchCount:0,fetchStartTimesMs:[]};return s.set(e,i),i},m=e=>{let t=Date.now(),n=o.get(e);if(r.minimumFetchIntervalMs>0&&n!==void 0&&t-n<r.minimumFetchIntervalMs)throw k4(`metadata document fetch is within the per-client minimum interval`);f(e,t);let i=new URL(e).origin,a=p(i,t);if(j4(c,t),l>=r.maximumConcurrentFetches)throw k4(`global metadata fetch concurrency limit exceeded`);if(a.activeFetchCount>=r.maximumConcurrentFetchesPerOrigin)throw k4(`metadata fetch concurrency limit exceeded for client origin`);if(c.length>=r.maximumFetchesPerMinute)throw k4(`global metadata fetch rate limit exceeded`);if(a.fetchStartTimesMs.length>=r.maximumFetchesPerOriginPerMinute)throw k4(`metadata fetch rate limit exceeded for client origin`);o.delete(e),o.set(e,t),c.push(t),a.fetchStartTimesMs.push(t),l+=1,a.activeFetchCount+=1;let s=!1;return()=>{s||(s=!0,--l,--a.activeFetchCount)}};return async(n,r,s)=>{if(!b4(r))return null;let c=n.context.getPlugin(`oauth-provider`);if(!c)throw new D(`cimd discovery invoked without the oauth-provider plugin installed`);let l=c.options,f=u(r),p=Date.now();if(f&&f.expiresAt>p)return s||D4(n,r,f.metadata,e,l);let h=a.get(r);if(h!==void 0)return h;let g=m(r),_=(async()=>{let a=await jye(n,r,e,f?{etag:f.etag,lastModified:f.lastModified}:void 0);if(a.status===`not-modified`&&!f)throw Mye(`Metadata document returned 304 without a validated cached document`);let c=a.status===`modified`?a.metadata:f.metadata,u=await D4(n,r,c,e,l,s??void 0),p=zye(c,a.status===`modified`?a.cacheHeaders:Rye(f.responseCacheHeaders,a.cacheHeaders),t,Date.now());return p?d(r,p):i.delete(r),o.delete(r),u})();a.set(r,_);try{return await _}catch(e){throw o.delete(r),o.set(r,Date.now()),e}finally{a.get(r)===_&&a.delete(r),g()}}}function Vye(e){return{id:w4,matches:b4,resolve:Bye(e),fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}}}const Hye=e=>{let t=Vye(e);return{id:`cimd`,version:`1.7.12`,init(e){Phe(e,{clientDiscovery:t})}}},Uye=/* @__PURE__ */ new Set([204,205,304]);function Wye(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.append(n,r);return t}const Gye=async(e,t)=>{let n=new Request(e,t),r=new URL(n.url);if(r.protocol!==`https:`)throw TypeError(`CIMD Node transport requires an HTTPS URL`);if(n.method!==`GET`&&n.method!==`HEAD`)throw TypeError(`CIMD Node transport supports only GET and HEAD`);let i=await _ee(r.hostname,{all:!0,verbatim:!0});if(i.length===0)throw TypeError(`metadata hostname returned no DNS addresses`);for(let e of i)if(!CY(e.address))throw TypeError(`metadata hostname must resolve only to public-routable addresses`);let a=i[0],o=Object.fromEntries(n.headers.entries());o.host=r.host;let s=t?.signal??(e instanceof Request?e.signal:n.signal);return new Promise((e,t)=>{let i=pee(r,{agent:!1,headers:o,method:n.method,servername:Tt(r.hostname.replace(/^\[|\]$/g,``))===0?r.hostname:void 0,signal:s,lookup:(e,t,n)=>{t.all?n(null,[a]):n(null,a.address,a.family)}},t=>{let r=t.statusCode??500,i=n.method===`HEAD`||Uye.has(r)?null:St.toWeb(t);e(new Response(i,{headers:Wye(t.headers),status:r,statusText:t.statusMessage}))});i.once(`error`,t),i.end()})};function Kye(e,t=8){let n=0;return(r,i)=>{let a=i?.signal??(r instanceof Request?r.signal:void 0);return a?.aborted?Promise.reject(a.reason):n>=t?Promise.reject(/* @__PURE__ */ Error(`CIMD transport capacity reached`)):(n++,new Promise((t,o)=>{let s=!1,c=()=>{s=!0,o(a?.reason)};a?.addEventListener(`abort`,c,{once:!0});let l=()=>{n--,a?.removeEventListener(`abort`,c)};Promise.resolve().then(()=>(a?.throwIfAborted(),e(r,i))).then(e=>{l(),s?e.body?.cancel().catch(()=>{}):t(e)},e=>{l(),o(e)})}))}}var N4=class e extends P()(`clankerauth/CimdTransport`){static layer=uf(e,{fetch:Kye(Gye)});static layerWith=t=>t===void 0?e.layer:uf(e,{fetch:t})};const P4=`x-clankerauth-peer`,qye=e=>dee({requestTimeout:15e3,headersTimeout:1e4},e),Jye=(e,t)=>{t.writeHead(503).end()},Yye=um(`NodeHttp.listen`)(function*(e,t){let n=Jye,r=qye((e,t)=>n(e,t)),i=$f(e=>{r.close(()=>e(L)),r.closeAllConnections()});yield*Bp($f(n=>{let i=e=>n(z(e));r.once(`error`,i),r.listen(e,t,()=>{r.off(`error`,i),n(L)})}),()=>i);let a=r.address();return a instanceof Object?{port:a.port,serve:e=>Vp(()=>i).pipe(cp(()=>I(()=>n=e)))}:yield*rp(/* @__PURE__ */ Error(`Expected a TCP listener`))}),Xye=ch(65536),Zye=/^\/forward-auth(?:\?|$)/,Qye=(e,t,n)=>{let r=(e[`x-forwarded-for`]?.split(`,`).map(e=>e.trim()).filter(Boolean))?.at(-1);return n&&r?r:Fi(t,()=>`unknown`)},$ye=({baseURL:e,trustProxy:t})=>n=>R(function*(){let r=yield*lM,i=r.source,a=i instanceof wt?i.url:r.url;if(!a?.startsWith(`/`)||a.startsWith(`//`))return aj({status:400});let o=zt(r.headers,Zye.test(a)?bg(`forwarded`):xg([`forwarded`,`x-forwarded-host`,`x-forwarded-proto`]),_g(`host`,new URL(e).host),_g(P4,Qye(r.headers,r.remoteAddress,t)),bg(`x-forwarded-for`)),s=yield*n.pipe(Lp(lM,r.modify({headers:o})),Lp(DA,Xye));return i instanceof wt?EO(s.body).pipe(OO(`Stream`,e=>vj(s,nA(e.stream.pipe(FE(()=>I(()=>i.socket.destroy()))),e.contentType,e.contentLength))),PO(()=>s)):s}).pipe(Jp),F4=e=>`${I4}${e}`,I4=`resource:`,L4=(e,t,n)=>e`DELETE FROM verification WHERE json_valid(value) AND json_extract(value, '$.type') = 'authorization_code' AND (${t} IS NULL OR json_extract(value, '$.query.client_id') = ${t}) AND (${n} IS NULL OR json_extract(value, '$.referenceId') = ${n})`,R4=um(`Authorization.clear`)(function*(e,t){let n=t.clientId??null,r=t.resource===void 0?null:F4(t.resource);yield*e`DELETE FROM oauthConsent WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*L4(e,n,r),yield*e`DELETE FROM oauthAccessToken WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*e`DELETE FROM oauthRefreshToken WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`}),ebe=Ooe(W({message:Mx(U),error_description:Mx(U)})),tbe=e=>Fi(Hi(ebe(e.body),e=>Li(e.message??e.error_description)),()=>`Request could not be completed`),z4=e=>new aV({message:e}),B4=e=>new $B({message:e}),V4=(e,t={})=>Xf({try:e,catch:e=>{if(!Rq(e))return QB.of(e);let n=e.statusCode,r=n===400||n===422?t.refused:n===404?t.missing:n===409?t.conflict:n===503?t.unavailable:void 0;return r?r(tbe(e)):QB.of(e)}}),H4=(e,t)=>new SI({message:t,issues:[{path:e,message:t}]}),nbe=Sx(K(JV)),rbe=ln(`RequestParseError`),ibe=e=>nbe(e)?e:vce(e)&&rbe(e.reason)?new oV({message:`Request body could not be read`}):QB.of(e),abe=new Map(JV.map(e=>[e,ob(`httpApiStatus`)(e.ast)??500])),obe=tce(K(JV)),U4=e=>{let t=ibe(e),n=JV.find(e=>Sx(e)(t));return obe(t,{status:abe.get(n)??500}).pipe(yp)},W4=(e,t)=>e===t||e.endsWith(`.${t}`),sbe=e=>{try{return new URL(`https://${e}`).hostname===e&&e.includes(`.`)&&!Tt(e)}catch{return!1}},G4=(e,t)=>e.protocol===`https:`||e.protocol===`http:`&&([`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||t),K4=`HTTPS origins (HTTP allowed on loopback, or anywhere with CLANKERAUTH_ALLOW_INSECURE_HTTP=true)`,q4=(e,t)=>URL.canParse(e)&&new URL(e).origin===e&&G4(new URL(e),t),J4=H(function*(e){let{allowInsecureHttp:t,baseURL:n,cookieDomain:r}=e;return q4(n,t)?cg(e.secret).length<32?yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BETTER_AUTH_SECRET must have at least 32 characters`)):e.mcpAllowedOrigins.every(e=>q4(e,t))?r!==void 0&&(!sbe(r)||!W4(new URL(n).hostname,r))?yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_COOKIE_DOMAIN must be a bare parent domain of the CLANKERAUTH_BASE_URL host, such as home.example`)):e:yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_MCP_ALLOWED_ORIGINS must contain exact ${K4}`)):yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BASE_URL must be one of: ${K4}`))}),cbe=R(function*(){let e={baseURL:yield*BD(`CLANKERAUTH_BASE_URL`),secret:yield*WD(`CLANKERAUTH_BETTER_AUTH_SECRET`),database:yield*BD(`CLANKERAUTH_DATABASE`).pipe(DD(`data/clankerauth.sqlite`)),host:yield*BD(`CLANKERAUTH_HOST`).pipe(DD(`127.0.0.1`)),port:yield*UD(`CLANKERAUTH_PORT`).pipe(DD(3e3)),mcpAllowedOrigins:yield*VD(xS,`CLANKERAUTH_MCP_ALLOWED_ORIGINS`).pipe(DD([])),trustProxy:yield*HD(`CLANKERAUTH_TRUST_PROXY`).pipe(DD(!1)),allowInsecureHttp:yield*HD(`CLANKERAUTH_ALLOW_INSECURE_HTTP`).pipe(DD(!1)),cookieDomain:yield*BD(`CLANKERAUTH_COOKIE_DOMAIN`).pipe(DD(void 0))};return yield*J4(e)});var Y4=class e extends P()(`clankerauth/Settings`){static layer=pf(e,cbe)};const X4=`Exactly one configured resource is required`,Z4=[`offline_access`],lbe=iH(bS(G(U))),ube=iH(W({identifier:U,name:U,allowedScopes:U})),Q4=iH(G(jV)),$4=(e,t)=>[.../* @__PURE__ */ new Set([...Z4,...t.flatMap(t=>e.find(e=>e.identifier===t)?.scopes??[])])],e3=um(`ResourceCatalog.validateSelection`)(function*(e,t){let n=t.findIndex(t=>!e.some(e=>e.identifier===t));if(n!==-1)return yield*H4([`resources`,n],`Unknown Resource`)}),t3=um(`ResourceCatalog.accessForClient`)(function*(e,t){return yield*Q4(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource WHERE clientId = ${e} ORDER BY resourceId`)});var n3=class e extends P()(`clankerauth/ResourceCatalog`){static layer=pf(e,R(function*(){let{sql:e}=yield*cH,t=fV((yield*Y4).baseURL),n=um(`ResourceCatalog.decode`)(function*(e){let n=yield*ube(e),r=yield*lbe(n.allowedScopes);return{identifier:n.identifier,name:n.name,scopes:r.filter(e=>!Z4.includes(e)),builtIn:n.identifier===t}}),r=um(`ResourceCatalog.list`)(function*(){let t=yield*e`SELECT identifier, name, allowedScopes FROM oauthResource ORDER BY createdAt, identifier`;return yield*qf(t,n)}),i=um(`ResourceCatalog.get`)(function*(t){let r=yield*e`SELECT identifier, name, allowedScopes FROM oauthResource WHERE identifier = ${t}`;return r[0]?yield*n(r[0]):void 0});return{list:r,get:i,application:e=>V(i(e),e=>e?.builtIn?void 0:e),access:um(`ResourceCatalog.access`)(function*(){return yield*Q4(yield*e`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource ORDER BY clientId, resourceId`)}),hasAccess:um(`ResourceCatalog.hasAccess`)(function*(t,n){return(yield*e`SELECT 1 FROM oauthClient c WHERE c.clientId = ${t} AND (c.userId IS NULL
|
|
511
|
+
OR EXISTS (SELECT 1 FROM oauthClientResource l WHERE l.clientId = c.clientId AND l.resourceId = ${n}))`).length>0}),scopesFor:um(`ResourceCatalog.scopesFor`)(function*(e){let t=yield*r();return yield*e3(t,e),$4(t,e)})}}))};const dbe=Doe(W({typ:U,payload:Gx(U,JS)})),fbe=e=>({id:`signer`,endpoints:{signDocument:X.serverOnly({method:`POST`,body:dbe},async t=>t.json({token:await w$(t,{options:e,header:{typ:t.body.typ},payload:t.body.payload})}))}}),pbe=e=>typeof e==`string`,mbe=(e,t,n,r,i,a)=>{let o={disableSettingJwtHeader:!0,jwt:{issuer:`${e.baseURL}/api/auth`},jwks:{keyPairConfig:{alg:`EdDSA`,crv:`Ed25519`}}},s=a4({loginPage:`/login`,consentPage:`/consent`,scopes:[...Z4],resources:[{identifier:fV(e.baseURL),name:`clankerauth administration`,allowedScopes:[...Z4,pV.read,pV.write]}],resourceSeedMode:`merge`,rateLimit:{register:{window:60,max:10}},postLogin:{page:`/consent`,shouldRedirect:()=>!1,consentReferenceId:async({scopes:e})=>{let t=await n4(),r=new URLSearchParams(t?.query),a=r.getAll(`resource`);if(a.length!==1||!await i(n.get(a[0])))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:X4});let o=r.get(`client_id`);if(!o||!await i(n.hasAccess(o,a[0])))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`Client access is required`});let s=await i(n.scopesFor(a));if(e.some(e=>!s.includes(e)))throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`Resource scopes changed; start authorization again`});return F4(a[0])}},grantTypes:[`authorization_code`,`refresh_token`],allowDynamicClientRegistration:!0,allowUnauthenticatedClientRegistration:!0,clientRegistrationRequirePKCE:!0,enforcePerClientResources:!1,accessTokenExpiresIn:900,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:30,codeExpiresIn:120,clientPrivileges:async({user:e,action:t})=>!!e&&t!==`configure-client-credentials-scopes`,resourcePrivileges:async({user:e})=>!!e});return{options:{appName:`clankerauth`,baseURL:e.baseURL,secret:cg(e.secret),database:{db:t,type:`sqlite`,transaction:!0},trustedOrigins:[e.baseURL],logger:{disabled:!0},disabledPaths:[`/token`],emailAndPassword:{enabled:!0,minPasswordLength:8,maxPasswordLength:128},databaseHooks:{user:{create:{before:async()=>{if(await a())throw new E(`CONFLICT`,{message:`Setup already completed`})}}}},hooks:{before:Hq(async e=>{if(e.path===`/oauth2/register`){let t=e.body.redirect_uris;!e.body.application_type&&Array.isArray(t)&&t.some(e=>{if(!pbe(e))return!1;try{return new URL(e).protocol!==`https:`}catch{return!1}})&&(e.body.application_type=`native`),delete e.body.resources}})},session:{expiresIn:2592e3,updateAge:86400},advanced:{ipAddress:{ipAddressHeaders:[P4]}},rateLimit:{enabled:!0,storage:`database`,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:5}}},plugins:[mhe({defaultPrefix:`clankerauth_`,maximumNameLength:100,enableSessionForAPIKeys:!1,keyExpiration:{defaultExpiresIn:null,minExpiresIn:0},rateLimit:{enabled:!1}}),whe(o),fbe(o),s,Hye({fetchClientMetadataResource:r,metadataProfile:`mcp-2026-07-28`,metadataRevalidationInterval:300,maxCacheEntries:1e3,metadataFetchPolicy:{maximumConcurrentFetches:8,maximumConcurrentFetchesPerOrigin:2,maximumFetchesPerMinute:60,maximumFetchesPerOriginPerMinute:15}})]},oauthPlugin:s}};var r3=class e extends P()(`clankerauth/Issuer`){static layer=pf(e,R(function*(){let e=yield*Y4,{kysely:t}=yield*cH,n=yield*n3,{fetch:r}=yield*N4,i=gie(yield*Ap()),{options:a,oauthPlugin:o}=mbe(e,t,n,r,i,async()=>await(await TH((await s.$context).adapter)).count({model:`user`})>0),{auth:s,context:c}=yield*um(`Auth.initialize`)(function*(){let e=yield*Xf(()=>DQ(a));if(e.schemaProblems.length)return yield*z(/* @__PURE__ */ Error(`Database schema requires manual repair`));yield*Xf(()=>e.runMigrations());let t=Nme(a),n=yield*Xf(()=>t.$context);return yield*Xf(()=>t.api.getJwks()),{auth:t,context:n}},Xp)();return{auth:s,context:c,publishScopes:e=>I(()=>{o.options.scopes=[...e]})}}))};const hbe=Cx(PV),gbe=Cx(W({id:U,key:U,referenceId:U,expiresAt:Zx(jS),permissions:Zx(bS(PV))})),i3=H(function*(e){return{keyId:e.id,name:e.name??``,enabled:e.enabled,permissions:yield*hbe(e.permissions??{}).pipe(pp(()=>dp(pm(`An API key's stored permissions do not decode; it is listed with none`,{keyId:e.id}),{}))),expiresAt:e.expiresAt?fh(e.expiresAt):null,createdAt:fh(e.createdAt)}});var a3=class e extends P()(`clankerauth/ApiKeys`){static layer=pf(e,R(function*(){let{auth:e}=yield*r3,{sql:t}=yield*cH,n=yield*n3,r=um(`ApiKeys.validate`)(function*(e){if(e!==void 0)for(let[t,r]of Object.entries(e)){let e=yield*n.get(t);if(e?.builtIn)return yield*H4([`permissions`,t],`Administration requires OAuth access tokens, not API keys`);if(!e||r.some(t=>!e.scopes.includes(t)))return yield*H4([`permissions`,t],`Select explicitly granted, currently available Resource scopes`)}});return{list:um(`ApiKeys.list`)(function*(){let{providerHeaders:t}=yield*cV,n=yield*t,r=yield*V4(()=>e.api.listApiKeys({headers:n,query:{sortBy:`createdAt`,sortDirection:`asc`}}));return{keys:yield*qf(r.apiKeys,i3)}}),create:um(`ApiKeys.create`)(function*(t){let n=yield*cV;yield*r(t.permissions);let i=t.expiresAt===null?null:(gh(t.expiresAt)-(yield*Ef))/1e3;if(i!==null&&i<1)return yield*H4([`expiresAt`],`Expiry must be in the future`);let a=yield*V4(()=>e.api.createApiKey({body:{userId:n.userId,name:t.name.trim(),permissions:Ea(t.permissions,e=>[...e]),expiresIn:i}}),{refused:z4});return{...yield*i3(a),key:a.key}}),update:um(`ApiKeys.update`)(function*(t){let n=yield*cV;return yield*r(t.permissions),yield*i3(yield*V4(()=>e.api.updateApiKey({body:{userId:n.userId,keyId:t.keyId,name:t.name?.trim(),enabled:t.enabled,permissions:t.permissions&&Ea(t.permissions,e=>[...e])}}),{refused:z4,missing:()=>nV.of(t.keyId)}))}),delete:um(`ApiKeys.delete`)(function*({keyId:t}){let{providerHeaders:n}=yield*cV,r=yield*n;return yield*V4(()=>e.api.deleteApiKey({headers:r,body:{keyId:t}}),{missing:()=>nV.of(t)}),{deleted:!0}}),keyList:um(`ApiKeys.keyList`)(function*(r){let i=yield*Ef,a=(yield*n.application(r))?.scopes??[],o=a.length?yield*t`
|
|
512
|
+
SELECT id, key, referenceId, expiresAt, permissions FROM apikey
|
|
513
|
+
WHERE enabled = 1 AND (expiresAt IS NULL OR expiresAt > ${new Date(i).toISOString()})
|
|
514
|
+
`:[],s=yield*qf(o,e=>R(function*(){let t=yield*gbe(e),n=(t.permissions?.[r]??[]).filter(e=>a.includes(e));return n.length?[yield*Xf(()=>qde(new Uint8Array(Buffer.from(t.key,`base64url`)),r,{keyId:t.id,ownerId:t.referenceId,scopes:n,expiresAt:t.expiresAt===null?null:gh(t.expiresAt)}))]:[]}).pipe(pp(()=>dp(pm(`An API key row cannot be listed; it is left out of key lists`,{keyId:e.id}),[])))),c=Math.floor(i/1e3),{token:l}=yield*V4(()=>e.api.signDocument({body:{typ:hI,payload:{aud:r,iat:c,exp:c+86400,keys:s.flat()}}}));return{list:l}})}}))};const o3=e=>e.userId===null,_be=iH(G(W({userId:Zx(U)}))),s3=um(`Clients.requireManaged`)(function*(e,t){let[n]=yield*_be(yield*t`SELECT userId FROM oauthClient WHERE clientId = ${e}`);if(!n)return yield*z(eV.of(e));if(o3(n))return yield*z(rV.of(e))}),vbe=iH(G(W({clientId:U}))),c3=e=>({identifier:encodeURIComponent(e)}),ybe=e=>{try{return new URL(e).href===e&&!e.includes(`#`)}catch{return!1}},bbe=um(`Resources.validateInput`)(function*(e){let t=e.identifier.trim(),n=e.name.trim(),r=[...new Set(e.scopes.map(e=>e.trim()))];if(!ybe(t))return yield*H4([`identifier`],`Resource identifiers must be absolute URIs in canonical form, without a fragment`);let i=e.scopes.findIndex(e=>Z4.includes(e.trim()));return i===-1?{identifier:t,name:n,scopes:r}:yield*H4([`scopes`,i],`offline_access is reserved`)});var l3=class e extends P()(`clankerauth/Resources`){static layer=pf(e,R(function*(){let{sql:e,transaction:t}=yield*cH,{auth:n,publishScopes:r}=yield*r3,i=yield*n3,a=yield*Aw(1),o=e=>a.withPermit(e),s=um(`Resources.syncClient`)(function*(e,t,n){let r=yield*t3(n,e),i=JSON.stringify($4(t,r.map(e=>e.resource)));yield*e`UPDATE oauthClient SET scopes = ${i}, updatedAt = ${yield*Ef} WHERE clientId = ${n} AND scopes IS NOT ${i}`}),c=um(`Resources.synchronize`)(function*(){let t=yield*i.list(),n=$4(t,t.map(e=>e.identifier));yield*r(n),yield*e`UPDATE oauthClient SET scopes = ${JSON.stringify(n)}, updatedAt = ${yield*Ef} WHERE userId IS NULL AND scopes IS NOT ${JSON.stringify(n)}`;for(let n of yield*vbe(yield*e`SELECT clientId FROM oauthClient WHERE userId IS NOT NULL ORDER BY clientId`))yield*s(e,t,n.clientId)}),l=e=>e?.builtIn?z(H4([`identifier`],`The administration Resource is fixed`)):L,u=B(cV,e=>e.providerHeaders);yield*c();let d=um(`Resources.link`)(function*(n,r){let a=yield*i.list();yield*e3(a,r);let o=yield*Ef;return yield*t(e=>R(function*(){let t=(yield*t3(n,e)).map(e=>e.resource);for(let i of t.filter(e=>!r.includes(e)))yield*e`DELETE FROM oauthClientResource WHERE clientId = ${n} AND resourceId = ${i}`,yield*R4(e,{clientId:n,resource:i});for(let t of r)yield*e`INSERT OR IGNORE INTO oauthClientResource (id, clientId, resourceId, createdAt)
|
|
515
|
+
VALUES (${crypto.randomUUID()}, ${n}, ${t}, ${new Date(o).toISOString()})`;yield*s(e,a,n)})),yield*t3(n,e)},o);return{link:d,get:um(`Resources.get`)(function*({identifier:e}){return(yield*i.get(e))??(yield*tV.of(e))}),put:um(`Resources.put`)(function*(e){let r=yield*bbe(e),a=yield*i.get(r.identifier);yield*l(a);let o=yield*u,s=[...Z4,...r.scopes];return a===void 0?(yield*t(e=>R4(e,{resource:r.identifier})),yield*V4(()=>n.api.adminCreateOAuthResource({headers:o,body:{identifier:r.identifier,name:r.name,allowedScopes:s}}),{refused:z4})):yield*V4(()=>n.api.adminUpdateOAuthResource({headers:o,params:c3(r.identifier),body:{name:r.name,allowedScopes:s}}),{refused:z4}),yield*c(),{resource:r,created:a===void 0}},o),delete:um(`Resources.delete`)(function*({identifier:e}){yield*l(yield*i.get(e));let r=yield*u;return yield*V4(()=>n.api.adminDeleteOAuthResource({headers:r,params:c3(e)}),{missing:()=>tV.of(e)}),yield*t(t=>R4(t,{resource:e})),yield*c(),{deleted:!0}},o),setAccess:um(`Resources.setAccess`)(function*({client_id:t,resources:n}){return yield*s3(t,e),{clientAccess:yield*d(t,n)}})}}))};const xbe=iH(G(W({client_id:U,resource:U,scopes:bS(G(U)),approvedAt:Zx(jS),refreshedAt:Zx(jS)}))),Sbe=iH(G(W({clientId:U,name:Zx(U),redirectUris:bS(G(U)),tokenEndpointAuthMethod:Zx(U),applicationType:Zx(U),scopes:Zx(bS(G(U))),grantTypes:Zx(bS(G(U))),disabled:Zx(Bx),clientDiscoveryId:Zx(U),userId:Zx(U)})));var u3=class e extends P()(`clankerauth/Clients`){static layer=pf(e,R(function*(){let{sql:e,transaction:t}=yield*cH,{auth:n}=yield*r3,{baseURL:r}=yield*Y4,i=yield*n3,a=yield*l3,o=um(`Clients.exists`)(function*(e,t){if(!(yield*t`SELECT 1 FROM oauthClient WHERE clientId = ${e}`).length)return yield*z(eV.of(e))}),s=um(`Clients.revoke`)(function*(e,t,n){return yield*o(e,n),yield*R4(n,{clientId:e,resource:t}),{revoked:!0}}),c=um(`Clients.connections`)(function*(){let t=new Date(yield*Ef).toISOString();return(yield*xbe(yield*e`WITH live AS (
|
|
516
|
+
SELECT clientId, referenceId, scopes, createdAt FROM oauthRefreshToken
|
|
517
|
+
WHERE revoked IS NULL AND expiresAt > ${t}
|
|
518
|
+
), held AS (
|
|
519
|
+
SELECT clientId, referenceId FROM oauthConsent
|
|
520
|
+
UNION SELECT clientId, referenceId FROM live
|
|
521
|
+
)
|
|
522
|
+
SELECT h.clientId AS client_id, r.identifier AS resource, c.updatedAt AS approvedAt,
|
|
523
|
+
COALESCE(c.scopes, (SELECT l.scopes FROM live l WHERE l.clientId = h.clientId
|
|
524
|
+
AND l.referenceId = h.referenceId ORDER BY l.createdAt DESC LIMIT 1)) AS scopes,
|
|
525
|
+
(SELECT MAX(l.createdAt) FROM live l WHERE l.clientId = h.clientId
|
|
526
|
+
AND l.referenceId = h.referenceId) AS refreshedAt
|
|
527
|
+
FROM held h
|
|
528
|
+
JOIN oauthResource r ON h.referenceId = ${I4} || r.identifier
|
|
529
|
+
LEFT JOIN oauthConsent c ON c.clientId = h.clientId AND c.referenceId = h.referenceId
|
|
530
|
+
ORDER BY client_id, resource`)).map(e=>({...e,scopes:e.scopes.filter(e=>!Z4.includes(e))}))});return{connections:c,list:um(`Clients.list`)(function*(){let{email:t}=yield*cV,n=yield*e`
|
|
531
|
+
SELECT clientId, name, redirectUris, tokenEndpointAuthMethod, applicationType, scopes,
|
|
532
|
+
grantTypes, disabled, clientDiscoveryId, userId
|
|
533
|
+
FROM oauthClient ORDER BY createdAt, clientId
|
|
534
|
+
`,a=(yield*Sbe(n)).map(e=>({client_id:e.clientId,onboarding:e.clientDiscoveryId===null?o3(e)?`dcr`:`managed`:`cimd`,blocked:e.disabled===1,client_name:e.name??void 0,redirect_uris:e.redirectUris,token_endpoint_auth_method:e.tokenEndpointAuthMethod??void 0,application_type:e.applicationType,scope:e.scopes?.join(` `),grant_types:e.grantTypes??void 0})),o=yield*Kf({resources:i.list(),clientAccess:i.access(),connections:c()});return{clients:a,resources:o.resources,clientAccess:o.clientAccess,connections:o.connections,email:t,issuer:`${r}/api/auth`}}),create:um(`Clients.create`)(function*(e){let{providerHeaders:t}=yield*cV,r=yield*i.scopesFor(e.resources),o=yield*t,s=yield*V4(()=>n.api.adminCreateOAuthClient({headers:o,body:{client_name:e.client_name,redirect_uris:[...e.redirect_uris],token_endpoint_auth_method:e.token_endpoint_auth_method,application_type:e.application_type,grant_types:[`authorization_code`,`refresh_token`],scope:r.join(` `),skip_consent:!0}}),{refused:z4});return yield*a.link(s.client_id,e.resources).pipe(bp(()=>V4(()=>n.api.deleteOAuthClient({headers:o,body:{client_id:s.client_id}})))),s}),update:um(`Clients.update`)(function*(t){yield*s3(t.client_id,e);let{providerHeaders:r}=yield*cV,i=yield*r;return yield*V4(()=>n.api.updateOAuthClient({headers:i,body:{client_id:t.client_id,update:{client_name:t.client_name,redirect_uris:[...t.redirect_uris],application_type:t.application_type}}}),{refused:z4,missing:()=>eV.of(t.client_id)})}),rotate:um(`Clients.rotate`)(function*(t){yield*s3(t.client_id,e);let{providerHeaders:r}=yield*cV,i=yield*r;return yield*V4(()=>n.api.rotateClientSecret({headers:i,body:t}),{refused:z4,missing:()=>eV.of(t.client_id)})}),revoke:({client_id:e,resource:n})=>t(t=>s(e,n,t)),delete:({client_id:e})=>t(t=>R(function*(){return yield*o(e,t),yield*L4(t,e,null),yield*t`DELETE FROM oauthClient WHERE clientId = ${e}`,{deleted:!0}})),block:({client_id:e,blocked:n})=>t(t=>R(function*(){return n?yield*s(e,void 0,t):yield*o(e,t),yield*t`UPDATE oauthClient SET disabled = ${+!!n}, updatedAt = ${yield*Ef} WHERE clientId = ${e}`,{blocked:n}}))}}))};const Cbe=[`/`,`/resources`,`/keys`,`/login`,`/setup`,`/consent`],wbe=({readOnly:e,mcp:t})=>({readOnlyHint:e,destructiveHint:t.destructiveHint??!e,idempotentHint:t.idempotentHint??!1,openWorldHint:t.openWorldHint??!0}),d3=`~effect/ai/AiError/Reason`;var Tbe=class extends (/*#__PURE__*/ HS(`effect/ai/AiError/ToolParameterValidationError`)({_tag:/*#__PURE__*/ tS(`ToolParameterValidationError`),toolName:U,description:U})){[d3]=d3;get isRetryable(){return!0}get message(){return`Invalid parameters for tool '${this.toolName}': ${this.description}`}};const f3=`~effect/rpc/RpcMiddleware`,Ebe=()=>(e,t)=>{let n=nr(),r;n!==0&&(rr(2),r=new globalThis.Error,rr(n));function i(){}let a=i;return Object.setPrototypeOf(i,Object.getPrototypeOf(P(e))),i.key=e,Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[f3]=f3,a.error=t?.error??Lx,a.requiredForClient=t?.requiredForClient??!1,i},p3=(e,t)=>{let n=I(t);return Mx(e).pipe(Boe({decode:ov(n),encode:tv()}),eS(n))},Z=e=>Mx(e).pipe($x(Px(Nx(e)),{decode:tv(),encode:iv(Hi(Ri))})),Dbe=/*#__PURE__*/ K([U,cS]),m3=/*#__PURE__*/ K([U,cS]);var h3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(/*#__PURE__*/ Kx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ Z(m3)}),[q]))}))){},g3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){},_3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){};const Obe=U;({...h3.fields});var v3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...g3.fields,nextCursor:/*#__PURE__*/ Z(Obe)}))){};const y3=/*#__PURE__*/ Xx([`user`,`assistant`]);var b3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({audience:/*#__PURE__*/ Z(/*#__PURE__*/ G(y3)),priority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),lastModified:/*#__PURE__*/ Z(U)}))){},x3=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/Icon`)({src:U,mimeType:/*#__PURE__*/ Z(U),sizes:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`light`,`dark`]))})){},S3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),version:U,icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),description:/*#__PURE__*/ Z(U),websiteUrl:/*#__PURE__*/ Z(U)}))){},C3=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ClientCapabilities`)({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),JS)),roots:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Vx)})),sampling:/*#__PURE__*/ Z(/*#__PURE__*/ W({context:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({}))})),elicitation:/*#__PURE__*/ Z(/*#__PURE__*/ W({form:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),url:/*#__PURE__*/ Z(/*#__PURE__*/ W({}))}))})){},kbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),JS)),logging:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),completions:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),prompts:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Vx)})),resources:/*#__PURE__*/ Z(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ Z(Vx),listChanged:/*#__PURE__*/ Z(Vx)})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Vx)}))}))){},w3=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/McpErrorBase`)({code:dS,message:U,data:/*#__PURE__*/ Z(Rx)})){};const T3=-32601,E3=-32602,D3=-32603,O3=-32020;var k3=class extends (/*#__PURE__*/ HS(`effect/ai/McpSchema/ParseError`)({...w3.fields,_tag:/*#__PURE__*/ tS(`ParseError`),code:/*#__PURE__*/ tS(-32700)})){},A3=class extends (/*#__PURE__*/ HS(`effect/ai/McpSchema/InvalidRequest`)({...w3.fields,_tag:/*#__PURE__*/ tS(`InvalidRequest`),code:/*#__PURE__*/ tS(-32600)})){},j3=class extends (/*#__PURE__*/ HS(`effect/ai/McpSchema/MethodNotFound`)({...w3.fields,_tag:/*#__PURE__*/ tS(`MethodNotFound`),code:/*#__PURE__*/ tS(T3)})){},M3=class extends (/*#__PURE__*/ HS(`effect/ai/McpSchema/InvalidParams`)({...w3.fields,_tag:/*#__PURE__*/ tS(`InvalidParams`),code:/*#__PURE__*/ tS(E3)})){},N3=class e extends (/*#__PURE__*/ HS(`effect/ai/McpSchema/InternalError`)({...w3.fields,_tag:/*#__PURE__*/ tS(`InternalError`),code:/*#__PURE__*/ tS(D3)})){static notImplemented=/*#__PURE__*/ new e({message:`Not implemented`})};const P3=/*#__PURE__*/ K([k3,A3,j3,M3,N3,w3]);var Abe=class extends (/*#__PURE__*/ J(`ping`,{success:/*#__PURE__*/ W({}),error:P3,payload:/*#__PURE__*/ Qx(h3)})){},jbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...g3.fields,protocolVersion:U,capabilities:kbe,serverInfo:S3,instructions:/*#__PURE__*/ Z(U)}))){},Mbe=class extends (/*#__PURE__*/ J(`initialize`,{success:jbe,error:P3,payload:{...h3.fields,protocolVersion:U,capabilities:C3,clientInfo:S3}})){},F3=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{..._3.fields,requestId:Dbe,reason:/*#__PURE__*/ Z(U)}})){},I3=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{..._3.fields,progressToken:m3,progress:cS,total:/*#__PURE__*/ Z(cS),message:/*#__PURE__*/ Z(U)}})){},Nbe=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/Resource`)({uri:U,name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),mimeType:/*#__PURE__*/ Z(U),annotations:/*#__PURE__*/ Z(b3),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),size:/*#__PURE__*/ Z(dS),_meta:/*#__PURE__*/ Z(q)})){},L3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)}))){},Pbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...L3.fields,text:U}))){},Fbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...L3.fields,blob:wS}))){};({...v3.fields}),{...v3.fields},{...g3.fields},{...h3.fields};var R3=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ Qx(_3)})){};({...h3.fields}),{...h3.fields};var z3=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{..._3.fields,uri:U}})){},Ibe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),required:/*#__PURE__*/ Z(Vx)}))){},Lbe=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/Prompt`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),arguments:/*#__PURE__*/ Z(/*#__PURE__*/ G(Ibe)),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),_meta:/*#__PURE__*/ Z(q)})){},B3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`text`),text:U,annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){},V3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`image`),data:wS,mimeType:U,annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){},H3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`audio`),data:wS,mimeType:U,annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){};const U3=/*#__PURE__*/ K([B3,V3,H3,class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`resource`),resource:/*#__PURE__*/ K([Pbe,Fbe]),annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){},class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...Nbe.fields,type:/*#__PURE__*/ tS(`resource_link`)}))){}]);({...v3.fields}),{...g3.fields},{...h3.fields};var W3=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ Qx(_3)})){},Rbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({title:/*#__PURE__*/ Z(U),readOnlyHint:/*#__PURE__*/ p3(Vx,It),destructiveHint:/*#__PURE__*/ p3(Vx,Ft),idempotentHint:/*#__PURE__*/ p3(Vx,It),openWorldHint:/*#__PURE__*/ p3(Vx,Ft)}))){};const G3=/*#__PURE__*/ Kx(/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,q)),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),[q]),K3=q;var q3=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/Tool`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),inputSchema:G3,outputSchema:/*#__PURE__*/ Z(K3),annotations:/*#__PURE__*/ Z(Rbe),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),_meta:/*#__PURE__*/ Z(q)})){};({...v3.fields});var J3=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/CallToolResult`)({...g3.fields,content:/*#__PURE__*/ G(U3),structuredContent:/*#__PURE__*/ Z(JS),isError:/*#__PURE__*/ Z(Vx)})){};({...h3.fields});var Y3=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ Qx(_3)})){};const X3=/*#__PURE__*/ Xx([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]);({...h3.fields});var Z3=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:/*#__PURE__*/ W({..._3.fields,level:X3,logger:/*#__PURE__*/ Z(U),data:Rx})})){};const Q3=/*#__PURE__*/ K([B3,V3,H3,class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ToolUseContent`)({type:/*#__PURE__*/ tS(`tool_use`),id:U,name:U,input:/*#__PURE__*/ Gx(U,zx),_meta:/*#__PURE__*/ Z(q)})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ToolResultContent`)({type:/*#__PURE__*/ tS(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(U3),structuredContent:/*#__PURE__*/ Z(JS),isError:/*#__PURE__*/ Z(Vx),_meta:/*#__PURE__*/ Z(q)})){}]);var zbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({role:y3,content:/*#__PURE__*/ K([Q3,/*#__PURE__*/ G(Q3)]),_meta:/*#__PURE__*/ Z(q)}))){},Bbe=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ToolChoice`)({mode:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`auto`,`required`,`none`]))})){},Vbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({name:/*#__PURE__*/ Z(U)}))){},Hbe=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ModelPreferences`)({hints:/*#__PURE__*/ Z(/*#__PURE__*/ G(Vbe)),costPriority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))})){},Ube=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/CreateMessageResult`)({role:y3,content:/*#__PURE__*/ K([Q3,/*#__PURE__*/ G(Q3)]),_meta:/*#__PURE__*/ Z(q),model:U,stopReason:/*#__PURE__*/ Z(U)})){},$3=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:Ube,error:P3,payload:{messages:/*#__PURE__*/ G(zbe),modelPreferences:/*#__PURE__*/ Z(/*#__PURE__*/ W(Hbe.fields)),systemPrompt:/*#__PURE__*/ Z(U),includeContext:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ Z(cS),maxTokens:dS,stopSequences:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,zx)),tools:/*#__PURE__*/ Z(/*#__PURE__*/ G(/*#__PURE__*/ W(q3.fields))),toolChoice:/*#__PURE__*/ Z(/*#__PURE__*/ W(Bbe.fields))}})){};({...g3.fields});var Wbe=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/Root`)({uri:U,name:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)})){},e6=class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ListRootsResult`)({roots:/*#__PURE__*/ G(Wbe)})){},t6=class extends (/*#__PURE__*/ J(`roots/list`,{success:e6,error:P3,payload:/*#__PURE__*/ Qx(h3)})){};const Gbe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Z(U),type:/*#__PURE__*/ tS(`object`),properties:/*#__PURE__*/ Gx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/LegacyTitledEnum`)({type:/*#__PURE__*/ tS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),default:/*#__PURE__*/ Z(U)})){},/* @__PURE__ */ K([class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/UntitledSingleSelectEnum`)({type:/*#__PURE__*/ tS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/TitledSingleSelectEnum`)({type:/*#__PURE__*/ tS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),oneOf:/*#__PURE__*/ G(/*#__PURE__*/ W({const:U,title:U})),default:/*#__PURE__*/ Z(U)})){}]),/* @__PURE__ */ K([class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/UntitledMultiSelectEnum`)({type:/*#__PURE__*/ tS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(dS),maxItems:/*#__PURE__*/ Z(dS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/TitledMultiSelectEnum`)({type:/*#__PURE__*/ tS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(dS),maxItems:/*#__PURE__*/ Z(dS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(/*#__PURE__*/ W({const:U,title:U}))}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){}])]),class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitationString`)({type:/*#__PURE__*/ tS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minLength:/*#__PURE__*/ Z(dS),maxLength:/*#__PURE__*/ Z(dS),format:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitationNumber`)({type:/*#__PURE__*/ Xx([`number`,`integer`]),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minimum:/*#__PURE__*/ Z(cS),maximum:/*#__PURE__*/ Z(cS),default:/*#__PURE__*/ Z(cS)})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitationBoolean`)({type:/*#__PURE__*/ tS(`boolean`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),default:/*#__PURE__*/ Z(Vx)})){}])),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),Kbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitRequestFormParams`)({...h3.fields,mode:/*#__PURE__*/ Z(/*#__PURE__*/ Fx(`form`)),message:U,requestedSchema:Gbe})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitRequestURLParams`)({...h3.fields,mode:/*#__PURE__*/ Fx(`url`),message:U,elicitationId:U,url:U})){}]),qbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitAcceptResult`)({...g3.fields,action:/*#__PURE__*/ Fx(`accept`),content:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx,/*#__PURE__*/ G(U)])))})){},class extends (/*#__PURE__*/ VS(`@effect/ai/McpSchema/ElicitDeclineResult`)({...g3.fields,action:/*#__PURE__*/ Xx([`cancel`,`decline`])})){}]);var n6=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:qbe,error:P3,payload:Kbe})){},Jbe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};n6.payloadSchema;var r6=class extends (/*#__PURE__*/ Bo(`McpReverseOperationUnsupported`)){},Ybe=class extends (/*#__PURE__*/ Bo(`McpReverseOperationError`)){},i6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpRequestContext`)){},a6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpServerClient`)){},o6=class extends (/*#__PURE__*/ Ebe()(`effect/ai/McpSchema/McpServerClientMiddleware`)){},Xbe=class extends (/*#__PURE__*/ pN(F3,I3,Z3,z3,R3,Y3,W3,Jbe)){},s6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/EnabledWhen`)){};const c6={Complete:e=>({_tag:`Complete`,value:e}),InputRequired:e=>({_tag:`InputRequired`,...e})};var Zbe=class extends (/*#__PURE__*/ Bo(`ResourceNotFound`)){},Qbe=class extends (/*#__PURE__*/ Bo(`ToolNotFound`)){},$be=class extends (/*#__PURE__*/ Bo(`InvalidToolInput`)){},exe=class extends (/*#__PURE__*/ Bo(`InvalidToolContinuation`)){},txe=class extends (/*#__PURE__*/ Bo(`ToolExecutionError`)){},l6=class extends (/*#__PURE__*/ Bo(`UnsupportedByProtocol`)){},nxe=class extends (/*#__PURE__*/ Bo(`PromptNotFound`)){};const u6=/*#__PURE__*/ Lo(),d6=/*#__PURE__*/ Lo(),rxe=/*#__PURE__*/ I(()=>{let e=/* @__PURE__ */ new Map,t=[],n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{tools:{register:t=>I(()=>{e.set(t.descriptor.name,t)}),list:t=>I(()=>{let n=[];for(let r of e.values())r.isVisible(t)&&n.push(r.descriptor);return n}),call:(t,n)=>Qf(()=>{let r=e.get(t.name);return r===void 0||!r.isVisible(n.protocol)?new Qbe({name:t.name}):r.handle(t,n)})},resources:{register:e=>I(()=>{let n=t.findIndex(t=>t.descriptor.uri===e.descriptor.uri);n===-1?t.push(e):t[n]=e}),registerTemplate:e=>I(()=>{let t=n.findIndex(t=>t.descriptor.uriTemplate===e.descriptor.uriTemplate);t===-1?n.push(e):n[t]=e}),list:e=>I(()=>t.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),listTemplates:e=>I(()=>n.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),read:H(function*(e,r){let i=t.find(t=>t.descriptor.uri===e);if(i!==void 0&&i.isVisible(r.protocol))return yield*i.read(r);for(let t of n){let n=t.match(e);if(n!==void 0&&t.isVisible(r.protocol))return yield*t.read(e,n,r)}return yield*new Zbe({uri:e})})},prompts:{register:e=>I(()=>{r.set(e.descriptor.name,e)}),list:e=>I(()=>Array.from(r.values()).filter(t=>t.isVisible(e)).map(e=>e.descriptor)),get:H(function*(e,t,n){let i=r.get(e);return i===void 0||!i.isVisible(n.protocol)?yield*new nxe({name:e}):yield*i.get(t,n)})},completions:{register:(e,t)=>I(()=>{i.set(e,t)}),complete:H(function*(e,t){let n=e.reference.type===`prompt`?`prompt/${e.reference.name}/${e.argument.name}`:`resource/${e.reference.uriTemplate}/${e.argument.name}`,r=i.get(n);if(r===void 0)return yield*new M3({message:`Unknown completion reference or argument`});let a=yield*r(e,t),o=xte(a.values,100);return{...a,values:o,hasMore:a.hasMore===!0||o.length<a.values.length}})},registrationPresence:I(()=>({tools:e.size>0,resources:t.length>0||n.length>0,prompts:r.size>0}))}}),ixe=/*#__PURE__*/ new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),f6={debug:{effect:`Debug`,order:0},info:{effect:`Info`,order:1},notice:{effect:`Info`,order:2},warning:{effect:`Warn`,order:3},error:{effect:`Error`,order:4},critical:{effect:`Fatal`,order:5},alert:{effect:`Fatal`,order:6},emergency:{effect:`Fatal`,order:7}},p6=e=>{let t=e.startsWith(`=?base64?`),n=e.endsWith(`?=`);if(!t||!n)return/^[\t\x20-\x7e]*$/.test(e)?e:void 0;let r=yh(e.slice(9,-2));if(!Ca(r))try{return ixe.decode(r.success)}catch{return}},m6=e=>({protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.initializePayload._meta}),h6=e=>({clientId:e.clientId,protocol:m6(e),requestContext:i6.of({clientId:e.clientId,protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata}),serverClient:e}),g6=e=>({clientId:e.clientId,protocol:{protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata},requestContext:e}),_6=(e,t)=>t._tag===`Complete`?F(t.value):z(new l6({protocolVersion:e,feature:`Client input`})),v6=e=>{let{content:t,structuredContent:n}=e;if(typeof n!=`string`||t.length!==1)return t;let[r]=t;return r.type===`text`&&r.text===JSON.stringify(n)?[{...r,text:n}]:t},y6=e=>sn(e)&&(e.type===`tool_use`||e.type===`tool_result`),b6=e=>sn(e)?e.tools!==void 0||e.toolChoice!==void 0?!0:Array.isArray(e.messages)?e.messages.some(e=>{if(!sn(e))return!1;let t=e.content;return Array.isArray(t)?t.some(y6):y6(t)}):!1:!1;var x6=class e extends (/*#__PURE__*/ Bo(`ProtocolError`)){static fromTool(t){let n=EO(t).pipe(OO(`ToolNotFound`,e=>`Tool '${e.name}' not found`),OO(`UnsupportedByProtocol`,e=>`${e.feature} is not supported by MCP ${e.protocolVersion}`),kO({InvalidToolInput:e=>e.message,InvalidToolContinuation:e=>e.message,ToolExecutionError:e=>e.message}),FO);return new e({code:t._tag===`ToolExecutionError`?D3:E3,message:n})}static fromFeature(t){if(N(t,`_tag`)){if(t._tag===`PromptNotFound`&&N(t,`name`)&&Jt(t.name))return new e({code:E3,message:`Prompt '${t.name}' not found`});if(t._tag===`ResourceNotFound`&&N(t,`uri`)&&Jt(t.uri))return new e({code:-32002,message:`Resource '${t.uri}' not found`})}let n=axe(t);return wa(n)?new e(n.success):new e({code:D3,message:`MCP feature handler failed`})}};const axe=/*#__PURE__*/ koe(/* @__PURE__ */ W({code:cS,message:U,data:/*#__PURE__*/ Mx(zx)})),oxe=e=>ln(e,`McpReverseOperationUnsupported`),S6=e=>t=>oxe(t)?t:new Ybe({operation:e,cause:t}),C6=(e,t,n)=>Dx(e)(n).pipe(B(Cx(t))),sxe=(e,t,n)=>Dx(e)(n).pipe(B(Cx(t,{onExcessProperty:`error`}))),w6=/*#__PURE__*/ um(function*(e,t){return d6.$match(t,{Cancelled:e=>({tag:F3._tag,payload:F3.payloadSchema.make({_meta:e.metadata,requestId:e.requestId,reason:e.reason})}),Progress:t=>({tag:I3._tag,payload:I3.payloadSchema.make({_meta:t.metadata,progressToken:t.progressToken,progress:t.progress,total:t.total,message:e.supportsProgressMessage?t.message:void 0})}),LoggingMessage:e=>({tag:Z3._tag,payload:Z3.payloadSchema.make({_meta:e.metadata,level:e.level,logger:e.logger,data:e.data})}),ResourceUpdated:e=>({tag:z3._tag,payload:z3.payloadSchema.make({_meta:e.metadata,uri:e.uri})}),ResourcesChanged:e=>({tag:R3._tag,payload:R3.payloadSchema.make({_meta:e.metadata})}),ToolsChanged:e=>({tag:Y3._tag,payload:Y3.payloadSchema.make({_meta:e.metadata})}),PromptsChanged:e=>({tag:W3._tag,payload:W3.payloadSchema.make({_meta:e.metadata})}),ElicitationComplete:()=>void 0})}),T6=e=>{switch(e._tag){case`ToolsChanged`:case`PromptsChanged`:case`ResourcesChanged`:case`ResourceUpdated`:return!0;default:return!1}},E6=e=>{let t=/* @__PURE__ */ new WeakMap,n=e=>{let n=t.get(e);if(n===void 0){let r=GS(e.payloadSchema);n={decode:Cx(r),encode:Ex(r)},t.set(e,n)}return n},r=(t,n,r)=>e.handlerRpcs===void 0||e.makeHandlers===void 0?L:n===void 0&&e.runtime._tag===`Stateful`?rp(`MCP sessionful handler installation requires a lifecycle runtime`):r.install(e,e.handlerRpcs,e.makeHandlers(t,e.runtime._tag===`Stateful`?n:void 0,r.context)),i=t=>Lle(e.serverRequestRpcs,{spanPrefix:`McpServer/Client`}).pipe(V(n=>e.toReverseClient(t,n)));return{...e,payloadCodecs:n,installHandlers:r,makeReverseClient:i}},D6=e=>`@effect/mcp/${encodeURIComponent(e.protocolVersion)}/`,cxe=/*#__PURE__*/ H(function*(e){if(e.length===0)return yield*new Cd(`MCP protocol declaration must contain at least one MCP protocol`);let t=Object.freeze(Array.from(e)),n=/* @__PURE__ */ new Map;for(let e of t){if(n.has(e.protocolVersion))return yield*new Cd(`Duplicate MCP protocol version: ${e.protocolVersion}`);n.set(e.protocolVersion,e)}let r=t[0].clientRpcs.prefix(D6(t[0]));for(let e=1;e<t.length;e++)r=r.merge(t[e].clientRpcs.prefix(D6(t[e])));return{protocols:t,clientRpcs:r,select:e=>n.get(e)??t[0],protocolForInternalTag:e=>t.find(t=>e.startsWith(D6(t)))??t[0],routeClientRequest:(e,t)=>({...t,tag:`${D6(e)}${t.tag}`}),handlerTarget:(e,t)=>({context:t,install:H(function*(t,n,i){let a=yield*n.toHandlers(i);for(let i of n.requests.values()){let n=r.requests.get(`${D6(t)}${i._tag}`),o=a.mapUnsafe.get(i.key);if(n===void 0||o===void 0)return yield*rp(`MCP handler registration invariant failed for ${t.protocolVersion}/${i._tag}`);e.set(n.key,o)}})})}}),O6=e=>({initializePayload:e.initializePayload,negotiatedProfile:e.negotiatedProfile,protocol:e.protocol,resourceSubscriptions:e.supportsResourceSubscriptions?/* @__PURE__ */ new Set:void 0,logLevel:{_tag:`Effect`,level:e.logLevel}}),lxe=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=(n,r)=>{let i=r[`mcp-session-id`];return i===void 0?t.get(n):e.get(i)};return{registerHttp:(t,n)=>{let r=O6(n);return e.set(t,r),r},registerConnection:(e,n)=>{let r=O6(n);return t.set(e,r),r},resolve:r,resolveSessionId:t=>e.get(t),terminateSession:t=>e.delete(t),setLogLevel:(e,t,n)=>I(()=>{let i=r(t,n);i!==void 0&&(i.logLevel={_tag:`Mcp`,level:e})}),subscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?z(new x6({code:T3,message:`Resource subscriptions are not supported`})):I(()=>i.add(e)).pipe(fp)},unsubscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?z(new x6({code:T3,message:`Resource subscriptions are not supported`})):I(()=>i.delete(e)).pipe(fp)},effectLogLevel:(e,t,n)=>{let i=r(e,t);return i?.logLevel._tag===`Mcp`?f6[i.logLevel.level].effect:i?.logLevel.level??n},canDeliver:(e,t,n,i)=>{let a=r(e,t);if(n._tag===`LoggingMessage`){let e=a?.logLevel;return e?._tag===`Mcp`?f6[n.level].order>=f6[e.level].order:xD(f6[n.level].effect,e?.level??i)}return n._tag!==`ResourceUpdated`||a?.resourceSubscriptions?.has(n.uri)===!0},markInitialized:e=>{n.add(e)},initializedClientIds:()=>n.values(),disconnect:e=>{t.delete(e),n.delete(e)}}},k6=`mcp-session-id`,A6=`mcp-protocol-version`,j6=`io.modelcontextprotocol/protocolVersion`,M6=`io.modelcontextprotocol/clientCapabilities`,N6=-32022,P6=e=>typeof e==`object`&&e?e:void 0,F6=e=>{let t=P6(e);return t!==void 0&&j6 in t?{present:!0,value:t[j6]}:{present:!1,value:void 0}},uxe=e=>F6(P6(P6(e)?.params)?._meta).present,dxe=e=>{switch(e){case`tools/call`:case`prompts/get`:return`name`;case`resources/read`:return`uri`;default:return}},I6=e=>({_tag:`Rejected`,status:400,error:{code:O3,message:e}}),L6=/*#__PURE__*/ pN(Abe),R6=e=>({_tag:`Stateful`,transport:e});var z6=class extends (/*#__PURE__*/ P()(`effect/ai/McpRuntime/ServerRuntime`)){};const B6=(e,t)=>e.find(e=>e.runtime._tag===`Stateful`&&e.protocolVersion===t)??e.find(e=>e.runtime._tag===`Stateful`),fxe=/*#__PURE__*/ H(function*(e){let t=e.find(e=>e.runtime._tag===`Stateful`)===void 0?void 0:lxe(),n=e.map(e=>e.protocolVersion),r,i;for(let t of e)if(t.runtime._tag===`Stateless`){if(r!==void 0)return yield*new Cd(`MCP runtime supports at most one stateless protocol`);r=t.runtime,i=t}let a=yield*cxe(e),o=/* @__PURE__ */ new Set,s=e=>({code:N6,message:`Unsupported protocol version '${e}'`,data:{supported:n,requested:e}}),c=(e,r)=>{let i=e[A6],a=e[k6],o=a===void 0?void 0:t?.resolveSessionId(a);if(a!==void 0&&o===void 0)return{_tag:`Rejected`,status:404};if(!r&&i!==void 0){if(!n.includes(i))return{_tag:`Rejected`,status:400,error:s(i)};if(o?.protocol.runtime.transport.http.requiresVersionHeader===!0&&i!==o.protocol.protocolVersion)return I6(`MCP-Protocol-Version header '${i}' does not match negotiated protocol version '${o.protocol.protocolVersion}'`)}return{_tag:`Accepted`,binding:o,protocol:o?.protocol}},l=(e,n)=>{let r=e[A6],a=P6(n),o=P6(P6(a?.params)?._meta),l=F6(o),u=a?.id,d=a?.jsonrpc===`2.0`&&a.method===`initialize`&&(typeof u==`string`||typeof u==`number`),f=a?.jsonrpc===`2.0`&&a.method===`notifications/cancelled`&&u===void 0;if(l.present||(!d||t===void 0)&&i!==void 0&&(r===i.protocolVersion||t===void 0&&a?.jsonrpc===`2.0`&&typeof a.method==`string`&&(typeof u==`string`||typeof u==`number`))){if(r===void 0)return I6(`MCP-Protocol-Version header is required`);if(!f&&(o===void 0||typeof l.value!=`string`))return{_tag:`Rejected`,status:400,error:{code:E3,message:`Required request metadata is missing`}};if((!f||l.present)&&l.value!==r)return I6(`MCP-Protocol-Version header does not match request metadata`);if(!f&&P6(o?.[M6])===void 0)return{_tag:`Rejected`,status:400,error:{code:E3,message:`${M6} request metadata is required`}};if(i===void 0||r!==i.protocolVersion)return{_tag:`Rejected`,status:400,error:s(r)};let t=a?.method;if(typeof t!=`string`||e[`mcp-method`]!==t)return I6(`Mcp-Method header does not match request method`);let n=dxe(t);if(n!==void 0){let t=P6(a?.params)?.[n],r=e[`mcp-name`];if(typeof t!=`string`||r===void 0||p6(r)!==t)return I6(`Mcp-Name header does not match request parameters`)}return{_tag:`Accepted`,binding:void 0,protocol:i}}return c(e,d)};return z6.of({protocols:a.protocols,clientRpcs:a.clientRpcs,selectProtocol:a.select,protocolForInternalTag:a.protocolForInternalTag,routeClientRequest:a.routeClientRequest,prepareRequest:H(function*(e,n,o){let c=P6(o.payload)?._meta,l=F6(c),u=typeof l.value==`string`?l.value:void 0,d=l.present?void 0:t?.resolve(e,n),f;if(l.present)f=a.protocols.find(e=>e.protocolVersion===u)??i??a.protocols[0];else if(d!==void 0)f=d.protocol;else if(o.tag===`initialize`){let e=o.payload?.protocolVersion,t=B6(a.protocols,e);if(t===void 0)return yield*new x6({code:N6,message:`initialize is not supported by the configured MCP protocols (requested '${e}')`});f=t}else f=o.tag===`ping`?B6(a.protocols,void 0)??a.protocols[0]:a.protocols[0];if(f.runtime._tag===`Stateful`)return{protocol:f,binding:d};if(o.isNotification&&o.tag===`notifications/cancelled`)return{protocol:f};if(r===void 0)return yield*rp(`MCP stateless runtime invariant failed`);if(u!==void 0&&u!==f.protocolVersion)return yield*new x6(s(u));let p=yield*r.profileFromRequestMetadata(c),m={protocolVersion:p.protocolVersion,clientCapabilities:p.clientCapabilities,clientInfo:p.clientInfo,requestMetadata:p.requestMetadata},h=i6.of({clientId:e,protocolVersion:m.protocolVersion,clientCapabilities:m.clientCapabilities,clientInfo:m.clientInfo,requestMetadata:m.requestMetadata});return{protocol:f,profile:m,requestContext:h}}),resolveRequest:(e,n)=>t?.resolve(e,n),admitHttp:(e,r)=>{let i=(e,t,n=null)=>({_tag:`Rejected`,response:t===void 0?aj({status:e}):uj({jsonrpc:`2.0`,id:n,error:t},{status:e})});if(Ca(r)){let t=e[A6];if(t!==void 0&&!n.includes(t))return i(400,s(t));let r=l(e,void 0);return r._tag===`Rejected`&&(r.error===void 0||r.error.code===-32020)?i(r.status,r.error):i(200,new k3({message:`Parse error`}))}let a=r.success;if(Array.isArray(a)){if(a.length===0)return i(400,new A3({message:`Invalid Request`}));let t=l(e,a);return t._tag===`Rejected`||a.some(uxe)||a.some(e=>N(e,`method`)&&e.method===`initialize`)||t.binding?.protocol.runtime.transport.jsonRpc.acceptsBatches!==!0?i(400):{_tag:`Accepted`,acknowledge:!a.some(e=>N(e,`method`)&&N(e,`id`)),isSubscription:!1}}let o=N(a,`id`),c=o&&(typeof a.id==`string`||typeof a.id==`number`)?a.id:null,u=N(a,`jsonrpc`)&&a.jsonrpc===`2.0`,d=!o||typeof a.id==`string`||typeof a.id==`number`,f=u&&d&&N(a,`method`)&&typeof a.method==`string`,p=o&&(typeof a.id==`string`||typeof a.id==`number`||a.id===null),m=N(a,`result`),h=N(a,`error`),g=u&&p&&m!==h,_=l(e,a);if(_._tag===`Rejected`)return i(_.status,_.error,c);if(!f&&!g)return i(200,new A3({message:`Invalid Request`}),c);let v=N(a,`method`)&&a.method===`initialize`,y=e[k6]!==void 0;return v&&y?i(400,new A3({message:`initialize must not include an MCP-Session-Id header`}),c):!v&&!y&&_.protocol?.runtime._tag!==`Stateless`?i(400,t===void 0?void 0:new A3({message:`MCP-Session-Id header is required; send initialize to start a session`}),c):f&&_.protocol?.runtime._tag===`Stateless`&&!(_.protocol.handlerRpcs?.requests.has(a.method)??_.protocol.clientRpcs.requests.has(a.method))?i(404,new j3({message:`Method not found: ${a.method}`}),c):{_tag:`Accepted`,acknowledge:!f||!o,isSubscription:N(a,`method`)&&a.method===`subscriptions/listen`}},effectLogLevel:(e,n,r)=>t?.effectLogLevel(e,n,r)??r,disconnect:e=>t?.disconnect(e),terminateHttpSession:e=>Qf(()=>{let n=e[k6];if(n===void 0)return F(aj({status:400}));let r=c(e,!1);if(r._tag===`Rejected`)return F(aj({status:r.status}));let i=r.binding;return t.terminateSession(n),dp(qf(o,e=>e(i),{discard:!0}),aj({status:204}))}),onSessionTerminated:e=>Bp(I(()=>{o.add(e)}),()=>I(()=>{o.delete(e)})),deliveryClientIds:()=>t?.initializedClientIds()??[],canDeliver:(e,n,r,i)=>t?.canDeliver(e,n,r,i)??!0,installHandlers:H(function*(e){let r=/* @__PURE__ */ new Map,i={subscribeServerNotifications:e.subscribeServerNotifications,getListChangeRevision:e.getListChangeRevision,...e.sendNotification===void 0?{}:{sendNotification:e.sendNotification},...e.markSubscriptionCancelled===void 0?{}:{markSubscriptionCancelled:e.markSubscriptionCancelled},...e.terminateSubscription===void 0?{}:{terminateSubscription:e.terminateSubscription},supportedVersions:n,serverInfo:e.serverInfo,registrationPresence:e.core.registrationPresence},o=a.handlerTarget(r,i);for(let n of a.protocols){if(n.runtime._tag===`Stateless`){yield*n.installHandlers(e.core,void 0,o);continue}if(t===void 0)return yield*rp(`MCP sessionful runtime invariant failed`);yield*o.install(n,L6,L6.of({ping:()=>F({})}));let r={initialize:H(function*(r,i,a){let o=yield*e.core.registrationPresence;return yield*ap(s=>{let c=ca(s.context,lM),l={completions:!0,logging:!0,...o.tools?{tools:{listChanged:!0}}:{},...o.resources?{resources:{listChanged:!0,subscribe:c===void 0}}:{},...o.prompts?{prompts:{listChanged:!0}}:{},...e.serverInfo.extensions?{extensions:e.serverInfo.extensions}:{}},u={initializePayload:Mbe.payloadSchema.make({protocolVersion:r,capabilities:i.clientCapabilities,clientInfo:i.clientInfo,_meta:i.requestMetadata}),negotiatedProfile:i,protocol:n,supportsResourceSubscriptions:c===void 0&&l.resources?.subscribe===!0,logLevel:e.defaultLogLevel};if(c!==void 0){let e=crypto.randomUUID();t.registerHttp(e,u),_M(c,(t,r)=>F(hj(r,{[k6]:e,[A6]:n.protocolVersion})))}else t.registerConnection(a,u);return F({capabilities:l,instructions:e.serverInfo.instructions,serverInfo:S3.make({name:e.serverInfo.name,version:e.serverInfo.version,description:e.serverInfo.description,websiteUrl:e.serverInfo.websiteUrl,icons:e.serverInfo.icons})})})}),setLogLevel:t.setLogLevel,subscribe:t.subscribe,unsubscribe:t.unsubscribe,clientNotification:H(function*(e,n){e._tag===`Initialized`&&t.markInitialized(n)})};yield*n.installHandlers(e.core,r,o)}return ta(r)})})}),V6=e=>pf(z6)(fxe(e)),H6=e=>Mx(e).pipe($x(Px(Nx(e)),{decode:tv(),encode:iv(Hi(Ri))})),U6=q,pxe=/*#__PURE__*/ K([U,cS]),W6=/*#__PURE__*/ K([U,cS]),G6=/*#__PURE__*/ Xx([`user`,`assistant`]),K6=/*#__PURE__*/ Xx([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),q6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ H6(/*#__PURE__*/ Kx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ H6(W6)}),[q]))}),J6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ H6(U6)}),Y6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ H6(U6)}),X6=/*#__PURE__*/ W({...q6.fields,cursor:/*#__PURE__*/ H6(U)}),Z6=/*#__PURE__*/ W({...Y6.fields,nextCursor:/*#__PURE__*/ H6(U)}),mxe=/*#__PURE__*/ W({extensions:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),JS)),experimental:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(U,U6)),roots:/*#__PURE__*/ H6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ H6(Vx)})),sampling:/*#__PURE__*/ H6(U6)}),hxe=/*#__PURE__*/ W({extensions:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),JS)),experimental:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(U,U6)),logging:/*#__PURE__*/ H6(U6),prompts:/*#__PURE__*/ H6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ H6(Vx)})),resources:/*#__PURE__*/ H6(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ H6(Vx),listChanged:/*#__PURE__*/ H6(Vx)})),tools:/*#__PURE__*/ H6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ H6(Vx)}))}),Q6=/*#__PURE__*/ W({code:dS,message:U,data:/*#__PURE__*/ H6(Rx)}),$6=/*#__PURE__*/ W({audience:/*#__PURE__*/ H6(/*#__PURE__*/ G(G6)),priority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))}),gxe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ H6(U),text:U}),_xe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ H6(U),blob:U}),vxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`text`),text:U,annotations:/*#__PURE__*/ H6($6)}),yxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`image`),data:U,mimeType:U,annotations:/*#__PURE__*/ H6($6)}),bxe=/*#__PURE__*/ W({uri:U,name:U,description:/*#__PURE__*/ H6(U),mimeType:/*#__PURE__*/ H6(U),size:/*#__PURE__*/ H6(cS),annotations:/*#__PURE__*/ H6($6)}),xxe=/*#__PURE__*/ W({uriTemplate:U,name:U,description:/*#__PURE__*/ H6(U),mimeType:/*#__PURE__*/ H6(U),annotations:/*#__PURE__*/ H6($6)}),e8=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ H6(U),required:/*#__PURE__*/ H6(Vx)}),Sxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ H6(U),arguments:/*#__PURE__*/ H6(/*#__PURE__*/ G(e8))}),Cxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ H6(U),inputSchema:/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(U,U6)),required:/*#__PURE__*/ H6(/*#__PURE__*/ G(U))})}),t8=/*#__PURE__*/ W({hints:/*#__PURE__*/ H6(/*#__PURE__*/ G(/* @__PURE__ */ W({name:/*#__PURE__*/ H6(U)}))),costPriority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))}),wxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`ref/prompt`),name:U}),n8=/*#__PURE__*/ W({uri:U,name:/*#__PURE__*/ H6(U)});({...Y6.fields}),{...Z6.fields},{...Z6.fields},{...Y6.fields},{...Z6.fields},{...Y6.fields},{...Z6.fields},{...Y6.fields},{...Y6.fields};const Txe=/*#__PURE__*/ W({...Y6.fields,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U),total:/*#__PURE__*/ H6(cS),hasMore:/*#__PURE__*/ H6(Vx)})}),Exe=/*#__PURE__*/ W({...Y6.fields,roots:/*#__PURE__*/ G(n8)});var r8=class extends (/*#__PURE__*/ J(`ping`,{success:Y6,error:Q6,payload:/*#__PURE__*/ Qx(q6)})){};({...q6.fields}),{...q6.fields};var i8=class extends (/*#__PURE__*/ J(`logging/setLevel`,{success:Y6,error:Q6,payload:{...q6.fields,level:K6}})){};({...q6.fields}),{...q6.fields};var a8=class extends (/*#__PURE__*/ J(`resources/subscribe`,{success:Y6,error:Q6,payload:{...q6.fields,uri:U}})){},o8=class extends (/*#__PURE__*/ J(`resources/unsubscribe`,{success:Y6,error:Q6,payload:{...q6.fields,uri:U}})){};({...q6.fields}),{...q6.fields};var s8=class extends (/*#__PURE__*/ J(`roots/list`,{success:Exe,error:Q6,payload:/*#__PURE__*/ Qx(q6)})){},c8=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...J6.fields,requestId:pxe,reason:/*#__PURE__*/ H6(U)}})){};({...J6.fields});var l8=class extends (/*#__PURE__*/ J(`notifications/initialized`,{payload:/*#__PURE__*/ Qx(J6)})){},u8=class extends (/*#__PURE__*/ J(`notifications/roots/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){},d8=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...J6.fields,level:K6,logger:/*#__PURE__*/ H6(U),data:Rx}})){},f8=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...J6.fields,uri:U}})){},p8=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){},m8=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){},h8=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){};const g8=H6,Dxe=/*#__PURE__*/ W({...hxe.fields,completions:/*#__PURE__*/ g8(/*#__PURE__*/ W({}))}),Oxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`audio`),data:U,mimeType:U,annotations:/*#__PURE__*/ g8($6)}),_8=/*#__PURE__*/ W({title:/*#__PURE__*/ g8(U),readOnlyHint:/*#__PURE__*/ g8(Vx),destructiveHint:/*#__PURE__*/ g8(Vx),idempotentHint:/*#__PURE__*/ g8(Vx),openWorldHint:/*#__PURE__*/ g8(Vx)});({...Cxe.fields}),{...Y6.fields},{...Y6.fields},{...Z6.fields},{...Y6.fields},{...Y6.fields},{...q6.fields},{...q6.fields},{...q6.fields},{...q6.fields};var v8=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...J6.fields,progressToken:W6,progress:cS,total:/*#__PURE__*/ g8(cS),message:/*#__PURE__*/ g8(U)}})){};const y8=`2025-06-18`,b8=H6,x8=q,S8=/*#__PURE__*/ b8(x8),C8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ b8(U),version:U}),w8=/*#__PURE__*/ W({...mxe.fields,elicitation:/*#__PURE__*/ b8(/*#__PURE__*/ W({}))}),T8=/*#__PURE__*/ W({audience:/*#__PURE__*/ b8(/*#__PURE__*/ G(G6)),priority:/*#__PURE__*/ b8(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))}),E8=/*#__PURE__*/ W({...bxe.fields,title:/*#__PURE__*/ b8(U),annotations:/*#__PURE__*/ b8(T8),_meta:S8}),D8=/*#__PURE__*/ W({...xxe.fields,title:/*#__PURE__*/ b8(U),annotations:/*#__PURE__*/ b8(T8),_meta:S8}),O8=/*#__PURE__*/ K([/* @__PURE__ */ W({...gxe.fields,_meta:S8}),/* @__PURE__ */ W({..._xe.fields,_meta:S8})]),kxe=/*#__PURE__*/ W({...e8.fields,title:/*#__PURE__*/ b8(U)}),k8=/*#__PURE__*/ W({...Sxe.fields,title:/*#__PURE__*/ b8(U),arguments:/*#__PURE__*/ b8(/*#__PURE__*/ G(kxe)),_meta:S8}),A8=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`resource`),resource:O8,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),Axe=/*#__PURE__*/ W({...E8.fields,type:/*#__PURE__*/ Fx(`resource_link`)}),j8=/*#__PURE__*/ W({...vxe.fields,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),M8=/*#__PURE__*/ W({...yxe.fields,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),N8=/*#__PURE__*/ W({...Oxe.fields,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),P8=/*#__PURE__*/ K([j8,M8,N8,A8,Axe]),F8=/*#__PURE__*/ K([j8,M8,N8]),jxe=/*#__PURE__*/ W({role:G6,content:P8}),Mxe=/*#__PURE__*/ W({role:G6,content:F8}),Nxe=/*#__PURE__*/ W({...Dxe.fields}),I8=/*#__PURE__*/ W({...Y6.fields,protocolVersion:U,capabilities:Nxe,serverInfo:C8,instructions:/*#__PURE__*/ b8(U)});var L8=class extends (/*#__PURE__*/ J(`initialize`,{success:I8,error:Q6,payload:{...q6.fields,protocolVersion:U,capabilities:w8,clientInfo:C8}})){};const R8=/*#__PURE__*/ Kx(/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,x8)),required:/*#__PURE__*/ b8(/*#__PURE__*/ G(U))}),[q]),z8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),inputSchema:R8,outputSchema:/*#__PURE__*/ b8(R8),annotations:/*#__PURE__*/ b8(_8),_meta:S8}),B8=/*#__PURE__*/ W({...Y6.fields,content:/*#__PURE__*/ G(P8),structuredContent:/*#__PURE__*/ b8(x8),isError:/*#__PURE__*/ b8(Vx)}),Pxe=/*#__PURE__*/ W({...Y6.fields,role:G6,content:F8,model:U,stopReason:/*#__PURE__*/ b8(U)});var V8=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:Pxe,error:Q6,payload:{...q6.fields,messages:/*#__PURE__*/ G(Mxe),modelPreferences:/*#__PURE__*/ b8(t8),systemPrompt:/*#__PURE__*/ b8(U),includeContext:/*#__PURE__*/ b8(/*#__PURE__*/ Xx([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ b8(cS),maxTokens:cS,stopSequences:/*#__PURE__*/ b8(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ b8(x8)}})){};const H8=/*#__PURE__*/ W({...wxe.fields,title:/*#__PURE__*/ b8(U)}),U8=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`ref/resource`),uri:U}),W8=Txe;var G8=class extends (/*#__PURE__*/ J(`completion/complete`,{success:W8,error:Q6,payload:{...q6.fields,ref:/*#__PURE__*/ K([H8,U8]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ b8(/*#__PURE__*/ W({arguments:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,U))}))}})){};const K8=/*#__PURE__*/ W({...Z6.fields,resources:/*#__PURE__*/ G(E8)}),q8=/*#__PURE__*/ W({...Z6.fields,resourceTemplates:/*#__PURE__*/ G(D8)}),J8=/*#__PURE__*/ W({...Y6.fields,contents:/*#__PURE__*/ G(O8)}),Y8=/*#__PURE__*/ W({...Z6.fields,prompts:/*#__PURE__*/ G(k8)}),X8=/*#__PURE__*/ W({...Y6.fields,description:/*#__PURE__*/ b8(U),messages:/*#__PURE__*/ G(jxe)}),Z8=/*#__PURE__*/ W({...Z6.fields,tools:/*#__PURE__*/ G(z8)});var Fxe=class extends (/*#__PURE__*/ J(`resources/list`,{success:K8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},Ixe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:q8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},Q8=class extends (/*#__PURE__*/ J(`resources/read`,{success:J8,error:Q6,payload:{...q6.fields,uri:U}})){},Lxe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:Y8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},Rxe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:X8,error:Q6,payload:{...q6.fields,name:U,arguments:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,U))}})){},zxe=class extends (/*#__PURE__*/ J(`tools/list`,{success:Z8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},$8=class extends (/*#__PURE__*/ J(`tools/call`,{success:B8,error:Q6,payload:{...q6.fields,name:U,arguments:/*#__PURE__*/ b8(x8)}})){};const Bxe=/*#__PURE__*/ W({...Y6.fields,action:/*#__PURE__*/ Xx([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx])))}),Vxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),minLength:/*#__PURE__*/ b8(dS),maxLength:/*#__PURE__*/ b8(dS),format:/*#__PURE__*/ b8(/*#__PURE__*/ Xx([`email`,`uri`,`date`,`date-time`]))}),/* @__PURE__ */ W({type:/*#__PURE__*/ Xx([`number`,`integer`]),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),minimum:/*#__PURE__*/ b8(cS),maximum:/*#__PURE__*/ b8(cS)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`boolean`),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),default:/*#__PURE__*/ b8(Vx)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ b8(/*#__PURE__*/ G(U))})])),required:/*#__PURE__*/ b8(/*#__PURE__*/ G(U))});var e5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Bxe,error:Q6,payload:{...q6.fields,message:U,requestedSchema:Vxe}})){},Hxe=class extends (/*#__PURE__*/ pN(r8,L8,G8,i8,Rxe,Lxe,Fxe,Ixe,Q8,a8,o8,$8,zxe)){},t5=class extends (/*#__PURE__*/ pN(c8,v8,l8,u8)){},Uxe=class extends (/*#__PURE__*/ pN(r8,V8,s8,e5)){},Wxe=class extends (/*#__PURE__*/ pN(c8,v8,d8,f8,p8,m8,h8)){};const n5=/*#__PURE__*/ (/* @__PURE__ */ Hxe.omit(`ping`).middleware(o6).add(r8)).merge(t5),r5=/*#__PURE__*/ n5.omit(`ping`),Gxe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||sn(e.properties)&&Object.values(e.properties).every(sn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Jt);return t&&n},Kxe=e=>({protocolVersion:y8,clientCapabilities:C3.make(e.capabilities),clientInfo:S3.make(e.clientInfo),requestMetadata:e._meta}),i5=(e,t)=>new r6({operation:e,protocolVersion:y8,reason:t}),a5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(i5(t,`Client did not advertise the ${n} capability`)),o5=/*#__PURE__*/ H(function*(e){return EO(e).pipe(DO({type:AO(`text`,`resource_link`)},e=>e),DO({type:AO(`image`,`audio`)},e=>({type:e.type,mimeType:e.mimeType,data:vh(e.data),annotations:e.annotations,_meta:e._meta})),DO({type:`resource`},e=>{let t=e.resource;return`text`in t?A8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):A8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:vh(t.blob)},annotations:e.annotations,_meta:e._meta})}),FO)}),qxe=e=>`text`in e?{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,text:e.text}:{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,blob:vh(e.blob)},Jxe=e=>e===void 0||Yxe(e)?e:void 0,Yxe=e=>sn(e),Xxe=/*#__PURE__*/ E6({protocolVersion:y8,runtime:/*#__PURE__*/ R6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:n5,clientNotificationRpcs:t5,serverRequestRpcs:Uxe,serverNotificationRpcs:Wxe,handlerRpcs:r5,makeHandlers:(e,t)=>r5.of({initialize:(e,{client:n})=>t.initialize(y8,Kxe(e),n.id).pipe(V(e=>I8.make({protocolVersion:y8,capabilities:{experimental:e.capabilities.experimental,extensions:e.capabilities.extensions,logging:e.capabilities.logging?{}:void 0,completions:e.capabilities.completions?{}:void 0,prompts:e.capabilities.prompts,resources:e.capabilities.resources,tools:e.capabilities.tools},serverInfo:e.serverInfo,instructions:e.instructions}))),"logging/setLevel":({level:e},{client:n,headers:r})=>t.setLogLevel(e,n.id,r).pipe(dp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(u6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(u6.Progress({progressToken:e.progressToken,progress:e.progress,total:e.total,message:e.message,metadata:e._meta}),n.id,r),"notifications/roots/list_changed":(e,{client:n,headers:r})=>t.clientNotification(u6.RootsChanged(),n.id,r),"resources/list":t=>a6.use(t=>e.resources.list(m6(t))).pipe(V(e=>K8.make({resources:e}))),"resources/templates/list":t=>a6.use(t=>e.resources.listTemplates(m6(t))).pipe(V(e=>q8.make({resourceTemplates:e}))),"resources/read":H(function*({uri:t}){let n=yield*a6,r=yield*e.resources.read(t,h6(n)).pipe(vp(x6.fromFeature));return J8.make({contents:r.contents.map(qxe),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(dp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(dp({})),"prompts/list":t=>a6.use(t=>e.prompts.list(m6(t))).pipe(V(e=>Y8.make({prompts:e}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*a6,i=yield*e.prompts.get(n,t??{},h6(r)).pipe(vp(x6.fromFeature));if(i._tag===`InputRequired`)return yield*x6.fromFeature(new l6({protocolVersion:y8,feature:`prompt input requirements`}));let a=i.value,o=yield*qf(a.messages,e=>o5(e.content).pipe(V(t=>({role:e.role,content:t})),vp(x6.fromTool)));return X8.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*a6,r=yield*e.completions.complete({reference:t.ref.type===`ref/prompt`?{type:`prompt`,name:t.ref.name,title:t.ref.title}:{type:`resourceTemplate`,uriTemplate:t.ref.uri},argument:t.argument,context:t.context?.arguments===void 0?void 0:{arguments:t.context.arguments},metadata:t._meta},h6(n)).pipe(vp(x6.fromFeature));return W8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*a6,n=yield*e.tools.list(m6(t));return Z8.make({tools:n.map(e=>z8.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:Gxe(e.outputSchema)?e.outputSchema:void 0,annotations:e.annotations===void 0?void 0:_8.make({title:e.annotations.title,readOnlyHint:e.annotations.readOnlyHint,destructiveHint:e.annotations.destructiveHint,idempotentHint:e.annotations.idempotentHint,openWorldHint:e.annotations.openWorldHint}),_meta:e._meta}))})}),"tools/call":H(function*(t){let n=yield*a6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},h6(n)).pipe(B(e=>_6(y8,e)),vp(x6.fromTool)),i=yield*qf(v6(r),o5).pipe(vp(x6.fromTool)),a=Jxe(r.structuredContent);return B8.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*a5(e,`roots/list`,`roots`);let r=yield*C6(t6.payloadSchema,s8.payloadSchema,n).pipe(vp(()=>i5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(vp(S6(`roots/list`)));return new e6({roots:i})}),createMessage:H(function*(n){yield*a5(e,`sampling/createMessage`,`sampling`);let r=yield*sxe($3.payloadSchema,V8.payloadSchema,n).pipe(vp(()=>i5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(vp(S6(`sampling/createMessage`)));return yield*C6(V8.successSchema,$3.successSchema,i).pipe(vp(()=>i5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*a5(e,`elicitation/create`,`elicitation`);let r=n.mode===`form`?boe(n,[`mode`]):n,i=yield*Cx(e5.payloadSchema,{onExcessProperty:`error`})(r).pipe(vp(()=>i5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(vp(S6(`elicitation/create`)));return yield*C6(e5.successSchema,n6.successSchema,a).pipe(vp(()=>i5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>w6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Cx(c8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),s5=`2025-11-25`,Q=H6,c5=q,l5=/*#__PURE__*/ Q(c5),u5=/*#__PURE__*/ W({src:U,mimeType:/*#__PURE__*/ Q(U),sizes:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Q(/*#__PURE__*/ Xx([`light`,`dark`]))}),d5=/*#__PURE__*/ W({...C8.fields,description:/*#__PURE__*/ Q(U),websiteUrl:/*#__PURE__*/ Q(U),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),Zxe=/*#__PURE__*/ W({...w8.fields,sampling:/*#__PURE__*/ Q(/*#__PURE__*/ W({context:/*#__PURE__*/ Q(c5),tools:/*#__PURE__*/ Q(c5)})),elicitation:/*#__PURE__*/ Q(/*#__PURE__*/ W({form:/*#__PURE__*/ Q(c5),url:/*#__PURE__*/ Q(c5)}))}),f5=/*#__PURE__*/ W({...T8.fields,lastModified:/*#__PURE__*/ Q(U)}),p5=/*#__PURE__*/ W({...E8.fields,annotations:/*#__PURE__*/ Q(f5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),m5=/*#__PURE__*/ W({...D8.fields,annotations:/*#__PURE__*/ Q(f5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),h5=/*#__PURE__*/ W({...k8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),g5=/*#__PURE__*/ W({...j8.fields,annotations:/*#__PURE__*/ Q(f5)}),_5=/*#__PURE__*/ W({...M8.fields,annotations:/*#__PURE__*/ Q(f5)}),v5=/*#__PURE__*/ W({...N8.fields,annotations:/*#__PURE__*/ Q(f5)}),y5=/*#__PURE__*/ W({...A8.fields,annotations:/*#__PURE__*/ Q(f5)}),b5=/*#__PURE__*/ K([g5,_5,v5,/* @__PURE__ */ W({...p5.fields,type:/*#__PURE__*/ Fx(`resource_link`)}),y5]),Qxe=/*#__PURE__*/ W({role:G6,content:b5}),x5=/*#__PURE__*/ W({...z8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),S5=/*#__PURE__*/ W({...B8.fields,content:/*#__PURE__*/ G(b5)});var $xe=class extends (/*#__PURE__*/ J(`tools/call`,{success:S5,error:Q6,payload:$8.payloadSchema})){};const C5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`tool_use`),id:U,name:U,input:c5,_meta:l5}),w5=/*#__PURE__*/ K([g5,_5,v5,C5,/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(b5),structuredContent:/*#__PURE__*/ Q(c5),isError:/*#__PURE__*/ Q(Vx),_meta:l5})]),T5=/*#__PURE__*/ W({role:G6,content:/*#__PURE__*/ K([w5,/*#__PURE__*/ G(w5)]),_meta:l5}),E5=/*#__PURE__*/ W({mode:/*#__PURE__*/ Q(/*#__PURE__*/ Xx([`auto`,`required`,`none`]))}),eSe=/*#__PURE__*/ W({...Y6.fields,...T5.fields,model:U,stopReason:/*#__PURE__*/ Q(U)});var D5=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:eSe,error:Q6,payload:{...V8.payloadSchema.fields,messages:/*#__PURE__*/ G(T5),maxTokens:dS,tools:/*#__PURE__*/ Q(/*#__PURE__*/ G(x5)),toolChoice:/*#__PURE__*/ Q(E5)}})){};const O5=/*#__PURE__*/ W({...n8.fields,_meta:l5}),tSe=/*#__PURE__*/ W({...Y6.fields,roots:/*#__PURE__*/ G(O5)});var k5=class extends (/*#__PURE__*/ J(`roots/list`,{success:tSe,error:Q6,payload:/*#__PURE__*/ Qx(q6)})){};const A5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minLength:/*#__PURE__*/ Q(dS),maxLength:/*#__PURE__*/ Q(dS),format:/*#__PURE__*/ Q(/*#__PURE__*/ Xx([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Q(U)}),j5=/*#__PURE__*/ W({type:/*#__PURE__*/ Xx([`number`,`integer`]),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minimum:/*#__PURE__*/ Q(cS),maximum:/*#__PURE__*/ Q(cS),default:/*#__PURE__*/ Q(cS)}),M5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`boolean`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),default:/*#__PURE__*/ Q(Vx)}),N5=/*#__PURE__*/ W({const:U,title:U}),P5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Q(U)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),oneOf:/*#__PURE__*/ G(N5),default:/*#__PURE__*/ Q(U)})]),F5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(dS),maxItems:/*#__PURE__*/ Q(dS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(dS),maxItems:/*#__PURE__*/ Q(dS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(N5)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))})]),I5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),default:/*#__PURE__*/ Q(U)}),nSe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Q(U),type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Gx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([I5,P5,F5]),A5,j5,M5])),required:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),rSe=/*#__PURE__*/ K([/* @__PURE__ */ W({...q6.fields,mode:/*#__PURE__*/ Q(/*#__PURE__*/ Fx(`form`)),message:U,requestedSchema:nSe}),/* @__PURE__ */ W({...q6.fields,mode:/*#__PURE__*/ Fx(`url`),message:U,elicitationId:U,url:U})]),iSe=/*#__PURE__*/ W({...Y6.fields,action:/*#__PURE__*/ Xx([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ Q(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx,/*#__PURE__*/ G(U)])))});var L5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:iSe,error:Q6,payload:rSe})){},aSe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};const R5=/*#__PURE__*/ W({...I8.fields,serverInfo:d5});var oSe=class extends (/*#__PURE__*/ J(`initialize`,{success:R5,error:Q6,payload:{...L8.payloadSchema.fields,capabilities:Zxe,clientInfo:d5}})){};const z5=/*#__PURE__*/ W({...Z6.fields,resources:/*#__PURE__*/ G(p5)}),B5=/*#__PURE__*/ W({...Z6.fields,resourceTemplates:/*#__PURE__*/ G(m5)}),V5=/*#__PURE__*/ W({...Z6.fields,prompts:/*#__PURE__*/ G(h5)}),H5=/*#__PURE__*/ W({...X8.fields,messages:/*#__PURE__*/ G(Qxe)}),U5=/*#__PURE__*/ W({...Z6.fields,tools:/*#__PURE__*/ G(x5)});var sSe=class extends (/*#__PURE__*/ J(`resources/list`,{success:z5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},cSe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:B5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},lSe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:V5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},uSe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:H5,error:Q6,payload:{...q6.fields,name:U,arguments:/*#__PURE__*/ Q(/*#__PURE__*/ Gx(U,U))}})){},dSe=class extends (/*#__PURE__*/ J(`tools/list`,{success:U5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},fSe=class extends (/*#__PURE__*/ pN(r8,oSe,G8,i8,uSe,lSe,sSe,cSe,Q8,a8,o8,$xe,dSe)){},W5=class extends (/*#__PURE__*/ pN(c8,v8,l8,u8)){},pSe=class extends (/*#__PURE__*/ pN(r8,D5,k5,L5)){},mSe=class extends (/*#__PURE__*/ pN(c8,v8,d8,f8,p8,m8,h8,aSe)){};const G5=/*#__PURE__*/ (/* @__PURE__ */ fSe.omit(`ping`).middleware(o6).add(r8)).merge(W5),K5=/*#__PURE__*/ G5.omit(`ping`),hSe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||sn(e.properties)&&Object.values(e.properties).every(sn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Jt);return t&&n},q5=(e,t)=>new r6({operation:e,protocolVersion:s5,reason:t}),J5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(q5(t,`Client did not advertise the ${n} capability`)),gSe=e=>e.stopReason===`toolUse`||(`type`in e.content?e.content.type===`tool_use`||e.content.type===`tool_result`:e.content.some(e=>e.type===`tool_use`||e.type===`tool_result`)),_Se=(e,t)=>{let n=e.clientCapabilities.elicitation;return n===void 0?!1:t===`form`?n.form!==void 0||n.url===void 0:n.url!==void 0},Y5=/*#__PURE__*/ H(function*(e){return EO(e).pipe(DO({type:AO(`text`,`resource_link`)},e=>e),DO({type:AO(`image`,`audio`)},e=>({type:e.type,mimeType:e.mimeType,data:vh(e.data),annotations:e.annotations,_meta:e._meta})),DO({type:`resource`},e=>{let t=e.resource;return`text`in t?y5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):y5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:vh(t.blob)},annotations:e.annotations,_meta:e._meta})}),FO)}),vSe=e=>e===void 0||ySe(e)?e:void 0,ySe=e=>sn(e),bSe=/*#__PURE__*/ E6({protocolVersion:s5,runtime:/*#__PURE__*/ R6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:G5,clientNotificationRpcs:W5,serverRequestRpcs:pSe,serverNotificationRpcs:mSe,handlerRpcs:K5,makeHandlers:(e,t)=>K5.of({initialize:(e,{client:n})=>t.initialize(s5,{protocolVersion:s5,clientCapabilities:C3.make(e.capabilities),clientInfo:S3.make(e.clientInfo),requestMetadata:e._meta},n.id).pipe(V(e=>R5.make({protocolVersion:s5,capabilities:{experimental:e.capabilities.experimental,extensions:e.capabilities.extensions,logging:e.capabilities.logging?{}:void 0,completions:e.capabilities.completions?{}:void 0,prompts:e.capabilities.prompts,resources:e.capabilities.resources,tools:e.capabilities.tools},serverInfo:e.serverInfo,instructions:e.instructions}))),"logging/setLevel":({level:e},{client:n,headers:r})=>t.setLogLevel(e,n.id,r).pipe(dp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(u6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(u6.Progress({progressToken:e.progressToken,progress:e.progress,total:e.total,message:e.message,metadata:e._meta}),n.id,r),"notifications/roots/list_changed":(e,{client:n,headers:r})=>t.clientNotification(u6.RootsChanged(),n.id,r),"resources/list":()=>a6.use(t=>e.resources.list(m6(t))).pipe(V(e=>z5.make({resources:e.map(e=>p5.make(e))}))),"resources/templates/list":()=>a6.use(t=>e.resources.listTemplates(m6(t))).pipe(V(e=>B5.make({resourceTemplates:e.map(e=>m5.make(e))}))),"resources/read":H(function*({uri:t}){let n=yield*a6,r=yield*e.resources.read(t,h6(n)).pipe(vp(x6.fromFeature));return J8.make({contents:r.contents.map(e=>`text`in e?{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,text:e.text}:{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,blob:vh(e.blob)}),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(dp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(dp({})),"prompts/list":()=>a6.use(t=>e.prompts.list(m6(t))).pipe(V(e=>V5.make({prompts:e.map(e=>h5.make(e))}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*a6,i=yield*e.prompts.get(n,t??{},h6(r)).pipe(vp(x6.fromFeature));if(i._tag===`InputRequired`)return yield*x6.fromFeature(new l6({protocolVersion:s5,feature:`prompt input requirements`}));let a=i.value,o=yield*qf(a.messages,e=>Y5(e.content).pipe(V(t=>({role:e.role,content:t})),vp(x6.fromTool)));return H5.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*a6,r=yield*e.completions.complete({reference:t.ref.type===`ref/prompt`?{type:`prompt`,name:t.ref.name,title:t.ref.title}:{type:`resourceTemplate`,uriTemplate:t.ref.uri},argument:t.argument,context:t.context?.arguments===void 0?void 0:{arguments:t.context.arguments},metadata:t._meta},h6(n)).pipe(vp(x6.fromFeature));return W8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*a6,n=yield*e.tools.list(m6(t));return U5.make({tools:n.map(e=>x5.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:hSe(e.outputSchema)?e.outputSchema:void 0,icons:e.icons,annotations:e.annotations===void 0?void 0:_8.make({title:e.annotations.title,readOnlyHint:e.annotations.readOnlyHint,destructiveHint:e.annotations.destructiveHint,idempotentHint:e.annotations.idempotentHint,openWorldHint:e.annotations.openWorldHint}),_meta:e._meta}))})}),"tools/call":H(function*(t){let n=yield*a6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},h6(n)).pipe(B(e=>_6(s5,e)),mp([`InvalidToolInput`,`ToolExecutionError`],e=>F(J3.make({content:[B3.make({type:`text`,text:e.message})],isError:!0}))),vp(x6.fromTool)),i=yield*qf(v6(r),Y5).pipe(vp(x6.fromTool)),a=vSe(r.structuredContent);return S5.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*J5(e,`roots/list`,`roots`);let r=yield*C6(t6.payloadSchema,k5.payloadSchema,n).pipe(vp(()=>q5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(vp(S6(`roots/list`)));return new e6({roots:i})}),createMessage:H(function*(n){if(yield*J5(e,`sampling/createMessage`,`sampling`),b6(n)&&e.clientCapabilities.sampling?.tools==null)return yield*q5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`);if((n.includeContext===`thisServer`||n.includeContext===`allServers`)&&e.clientCapabilities.sampling?.context==null)return yield*q5(`sampling/createMessage`,`Client did not advertise the sampling.context capability`);let r=yield*C6($3.payloadSchema,D5.payloadSchema,n).pipe(vp(()=>q5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(vp(S6(`sampling/createMessage`)));return gSe(i)&&e.clientCapabilities.sampling?.tools==null?yield*q5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`):yield*C6(D5.successSchema,$3.successSchema,i).pipe(vp(()=>q5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*J5(e,`elicitation/create`,`elicitation`);let r=n.mode===`url`?`url`:`form`;if(!_Se(e,r))return yield*q5(`elicitation/create`,`Client did not advertise the elicitation.${r} capability`);let i=yield*C6(n6.payloadSchema,L5.payloadSchema,n).pipe(vp(()=>q5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(vp(S6(`elicitation/create`)));return yield*C6(L5.successSchema,n6.successSchema,a).pipe(vp(()=>q5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>e._tag===`ElicitationComplete`?F({tag:`notifications/elicitation/complete`,payload:{elicitationId:e.elicitationId}}):w6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Cx(c8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),X5=`2026-07-28`,$=H6,Z5=/*#__PURE__*/ $(q),Q5=/*#__PURE__*/ K([U,dS]),$5=Q5,e7=G6,t7=K6,n7=d5,xSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,q)),roots:/*#__PURE__*/ $(/*#__PURE__*/ W({})),sampling:/*#__PURE__*/ $(/*#__PURE__*/ W({context:/*#__PURE__*/ $(q),tools:/*#__PURE__*/ $(q)})),elicitation:/*#__PURE__*/ $(/*#__PURE__*/ W({form:/*#__PURE__*/ $(q),url:/*#__PURE__*/ $(q)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,q))}),[q]),SSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,q)),logging:/*#__PURE__*/ $(q),completions:/*#__PURE__*/ $(q),prompts:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Vx)})),resources:/*#__PURE__*/ $(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ $(Vx),listChanged:/*#__PURE__*/ $(Vx)})),tools:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Vx)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,q))}),[q]),r7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ $($5),"io.modelcontextprotocol/protocolVersion":U,"io.modelcontextprotocol/clientInfo":/*#__PURE__*/ $(n7),"io.modelcontextprotocol/clientCapabilities":xSe,"io.modelcontextprotocol/logLevel":/*#__PURE__*/ $(t7)}),[q]),i7=/*#__PURE__*/ W({_meta:r7}),a7=/*#__PURE__*/ W({_meta:/*#__PURE__*/ $(/* @__PURE__ */ Kx(/*#__PURE__*/ W({"io.modelcontextprotocol/subscriptionId":/*#__PURE__*/ $(Q5)}),[q]))}),o7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":n7}),[q]),s7={_meta:o7,resultType:/*#__PURE__*/ Fx(`complete`)},c7=/*#__PURE__*/ W({code:dS,message:U,data:/*#__PURE__*/ $(JS)}),CSe=f5,l7=/*#__PURE__*/ W({...p5.fields,size:/*#__PURE__*/ $(dS),annotations:/*#__PURE__*/ $(CSe)}),u7=m5,wSe=O8,d7=g5,f7=_5,p7=v5,m7=/*#__PURE__*/ K([d7,f7,p7,/* @__PURE__ */ W({...l7.fields,type:/*#__PURE__*/ Fx(`resource_link`)}),y5]),h7=h5,TSe=/*#__PURE__*/ W({role:e7,content:m7}),ESe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ Fx(`object`)}),[q]),DSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U)}),[q]),OSe=_8,g7=/*#__PURE__*/ W({...x5.fields,inputSchema:ESe,outputSchema:/*#__PURE__*/ $(DSe),annotations:/*#__PURE__*/ $(OSe)}),_7=/*#__PURE__*/ K([d7,f7,p7,C5,/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(m7),structuredContent:/*#__PURE__*/ $(JS),isError:/*#__PURE__*/ $(Vx),_meta:Z5})]),v7=/*#__PURE__*/ W({role:e7,content:/*#__PURE__*/ K([_7,/*#__PURE__*/ G(_7)]),_meta:Z5}),kSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({name:/*#__PURE__*/ $(U)}),[q]),y7=/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})),ASe=/*#__PURE__*/ W({...t8.fields,hints:/*#__PURE__*/ $(/*#__PURE__*/ G(kSe)),costPriority:/*#__PURE__*/ $(y7),speedPriority:/*#__PURE__*/ $(y7),intelligencePriority:/*#__PURE__*/ $(y7)}),jSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Fx(`sampling/createMessage`),params:/*#__PURE__*/ W({messages:/*#__PURE__*/ G(v7),modelPreferences:/*#__PURE__*/ $(ASe),systemPrompt:/*#__PURE__*/ $(U),includeContext:/*#__PURE__*/ $(/*#__PURE__*/ Xx([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ $(cS),maxTokens:dS,stopSequences:/*#__PURE__*/ $(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ $(q),tools:/*#__PURE__*/ $(/*#__PURE__*/ G(g7)),toolChoice:/*#__PURE__*/ $(E5)})}),MSe=/*#__PURE__*/ W({...v7.fields,model:U,stopReason:/*#__PURE__*/ $(U)}),NSe=O5,PSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Fx(`roots/list`),params:/*#__PURE__*/ $(/*#__PURE__*/ W({_meta:Z5}))}),FSe=/*#__PURE__*/ W({roots:/*#__PURE__*/ G(NSe)}),ISe=/*#__PURE__*/ W({method:/*#__PURE__*/ Fx(`elicitation/create`),params:/* @__PURE__ */ K([/* @__PURE__ */ W({mode:/*#__PURE__*/ $(/*#__PURE__*/ Fx(`form`)),message:U,requestedSchema:/* @__PURE__ */ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Gx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([I5,P5,F5]),A5,j5,M5])),required:/*#__PURE__*/ $(/*#__PURE__*/ G(U))})}),/* @__PURE__ */ W({mode:/*#__PURE__*/ Fx(`url`),message:U,url:U})])}),LSe=/*#__PURE__*/ W({action:/*#__PURE__*/ Xx([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx,/*#__PURE__*/ G(U)])))}),RSe=/*#__PURE__*/ K([jSe,PSe,ISe]),zSe=/*#__PURE__*/ K([MSe,FSe,LSe]),b7=/*#__PURE__*/ Gx(U,RSe),BSe=/*#__PURE__*/ Gx(U,zSe),x7={_meta:o7,resultType:/*#__PURE__*/ Fx(`input_required`)},S7=/*#__PURE__*/ K([/*#__PURE__*/ Kx(/*#__PURE__*/ W({...x7,inputRequests:b7,requestState:/*#__PURE__*/ $(U)}),[q]),/*#__PURE__*/ Kx(/*#__PURE__*/ W({...x7,inputRequests:/*#__PURE__*/ $(b7),requestState:U}),[q])]),C7={...i7.fields,inputResponses:/*#__PURE__*/ $(BSe),requestState:/*#__PURE__*/ $(U)},w7={...s7,ttlMs:/*#__PURE__*/ dS.check(/*#__PURE__*/ Goe(0)),cacheScope:/*#__PURE__*/ Xx([`public`,`private`])},T7={...i7.fields,cursor:/*#__PURE__*/ $(U)},E7={...s7,nextCursor:/*#__PURE__*/ $(U)},D7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...w7,supportedVersions:/*#__PURE__*/ G(U),capabilities:SSe,instructions:/*#__PURE__*/ $(U)}),[q]);var VSe=class extends (/*#__PURE__*/ J(`server/discover`,{success:D7,error:c7,payload:i7})){};const O7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,resources:/*#__PURE__*/ G(l7)}),[q]);var HSe=class extends (/*#__PURE__*/ J(`resources/list`,{success:O7,error:c7,payload:T7})){};const k7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,resourceTemplates:/*#__PURE__*/ G(u7)}),[q]);var USe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:k7,error:c7,payload:T7})){};const A7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...w7,contents:/*#__PURE__*/ G(wSe)}),[q]);var WSe=class extends (/*#__PURE__*/ J(`resources/read`,{success:/*#__PURE__*/ K([A7,S7]),error:c7,payload:{...C7,uri:U}})){};const j7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,prompts:/*#__PURE__*/ G(h7)}),[q]);var GSe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:j7,error:c7,payload:T7})){};const M7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...s7,description:/*#__PURE__*/ $(U),messages:/*#__PURE__*/ G(TSe)}),[q]);var KSe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:/*#__PURE__*/ K([M7,S7]),error:c7,payload:{...C7,name:U,arguments:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,U))}})){};const N7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,tools:/*#__PURE__*/ G(g7)}),[q]);var qSe=class extends (/*#__PURE__*/ J(`tools/list`,{success:N7,error:c7,payload:T7})){};const P7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...s7,content:/*#__PURE__*/ G(m7),structuredContent:/*#__PURE__*/ $(JS),isError:/*#__PURE__*/ $(Vx)}),[q]);var JSe=class extends (/*#__PURE__*/ J(`tools/call`,{success:/*#__PURE__*/ K([P7,S7]),error:c7,payload:{...C7,name:U,arguments:/*#__PURE__*/ $(q)}})){};const YSe=H8,XSe=U8,F7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...s7,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U).check(/*#__PURE__*/ mS(100)),total:/*#__PURE__*/ $(dS),hasMore:/*#__PURE__*/ $(Vx)})}),[q]);var ZSe=class extends (/*#__PURE__*/ J(`completion/complete`,{success:F7,error:c7,payload:{...i7.fields,ref:/*#__PURE__*/ K([YSe,XSe]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ $(/*#__PURE__*/ W({arguments:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,U))}))}})){};const I7=/*#__PURE__*/ W({toolsListChanged:/*#__PURE__*/ $(Vx),promptsListChanged:/*#__PURE__*/ $(Vx),resourcesListChanged:/*#__PURE__*/ $(Vx),resourceSubscriptions:/*#__PURE__*/ $(/*#__PURE__*/ G(U))}),L7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({_meta:/* @__PURE__ */ Kx(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":n7,"io.modelcontextprotocol/subscriptionId":Q5}),[q]),resultType:/*#__PURE__*/ Fx(`complete`)}),[q]);var QSe=class extends (/*#__PURE__*/ J(`subscriptions/listen`,{success:L7,error:c7,payload:{...i7.fields,notifications:I7}})){},R7=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...a7.fields,requestId:Q5,reason:/*#__PURE__*/ $(U)}})){},$Se=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...a7.fields,progressToken:$5,progress:cS,total:/*#__PURE__*/ $(cS),message:/*#__PURE__*/ $(U)}})){},eCe=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...a7.fields,level:t7,logger:/*#__PURE__*/ $(U),data:JS}})){},z7=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...a7.fields,uri:U}})){},B7=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ Qx(a7)})){},V7=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ Qx(a7)})){},H7=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ Qx(a7)})){},U7=class extends (/*#__PURE__*/ J(`notifications/subscriptions/acknowledged`,{payload:{...a7.fields,notifications:I7}})){},W7=class extends (/*#__PURE__*/ pN(VSe,ZSe,KSe,GSe,HSe,USe,WSe,QSe,JSe,qSe)){},G7=class extends (/*#__PURE__*/ pN(R7)){},tCe=class extends (/*#__PURE__*/ W7.merge(G7)){},nCe=class extends (/*#__PURE__*/ pN()){},rCe=class extends (/*#__PURE__*/ pN(R7,$Se,eCe,z7,B7,V7,H7,U7)){};const iCe=/*#__PURE__*/ Gx(U,q),aCe=/*#__PURE__*/ Cx(r7),oCe=/*#__PURE__*/ Cx(R7.payloadSchema),sCe=/*#__PURE__*/ Sx(JS),K7=/*#__PURE__*/ Dx(n7),q7=e=>{let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t},cCe=(e,t)=>{if(rn(t))return e===void 0;if(e===void 0)return!1;let n=p6(e);return n!==void 0&&EO(t).pipe(DO(jO,e=>n===e),DO(NO,e=>n===String(e)),DO(MO,e=>Number.isSafeInteger(e)&&n.trim().length>0&&Number(n)===e),PO(()=>!1))},lCe=/*#__PURE__*/ H(function*(e){let t=yield*aCe(e);return{protocolVersion:X5,clientCapabilities:t[`io.modelcontextprotocol/clientCapabilities`],clientInfo:t[`io.modelcontextprotocol/clientInfo`],requestMetadata:t}}),J7=(e,t)=>{let n=e._meta;return{...sn(n)?n:{},"io.modelcontextprotocol/serverInfo":t}},Y7=(e,t)=>q7({_meta:{"io.modelcontextprotocol/serverInfo":t},resultType:`input_required`,inputRequests:e.inputRequests,requestState:e.requestState}),X7=/*#__PURE__*/ Cx(/*#__PURE__*/ K([P7,S7])),Z7=/*#__PURE__*/ H(function*(e,t){let n=yield*K7(t);return e._tag===`Complete`?yield*X7({...q7(e.value),_meta:J7(e.value,n),resultType:`complete`}):yield*X7(Y7(e,n))}),uCe=(e,t)=>{let n={};for(let r of Object.values(e??{}))EO(r).pipe(DO({method:`roots/list`},()=>{t.roots===void 0&&(n.roots={})}),DO({method:`sampling/createMessage`},e=>{let r=n.sampling??{};b6(e.params)&&t.sampling?.tools===void 0&&(r.tools={}),(e.params.includeContext===`thisServer`||e.params.includeContext===`allServers`)&&t.sampling?.context===void 0&&(r.context={}),(t.sampling===void 0||Object.keys(r).length>0)&&(n.sampling=r)}),DO({method:`elicitation/create`},e=>{let r=e.params.mode===`url`?`url`:`form`,i=t.elicitation;i!==void 0&&(r===`url`?i.url!==void 0:i.form!==void 0||Object.keys(i).length===0)||((n.elicitation??={})[r]={})}),FO);return n},Q7=e=>q7({uri:e.uri,mimeType:e.mimeType,_meta:e._meta,...`text`in e?{text:e.text}:{blob:vh(e.blob)}}),$7=/*#__PURE__*/ TO().pipe(/*#__PURE__*/ DO({type:/*#__PURE__*/ AO(`text`,`resource_link`)},e=>e),/*#__PURE__*/ DO({type:/*#__PURE__*/ AO(`image`,`audio`)},e=>q7({type:e.type,mimeType:e.mimeType,data:vh(e.data),annotations:e.annotations,_meta:e._meta})),/*#__PURE__*/ DO({type:`resource`},e=>q7({type:`resource`,resource:Q7(e.resource),annotations:e.annotations,_meta:e._meta})),FO),dCe=e=>l7.make(e),fCe=e=>u7.make(e),pCe=e=>C6(Lbe,h7,e),mCe=e=>C6(q3,g7,e),e9={ttlMs:0,cacheScope:`private`},t9=/*#__PURE__*/ H(function*(e,t){let n=yield*K7(t);return{...q7(e),_meta:J7(e,n),resultType:`complete`}}),hCe=/*#__PURE__*/ TO().pipe(/*#__PURE__*/ OO(`ResourceNotFound`,e=>new x6({code:-32602,message:`Resource '${e.uri}' not found`,data:{uri:e.uri}})),/*#__PURE__*/ OO(`ToolNotFound`,`InvalidToolInput`,`InvalidToolContinuation`,`ToolExecutionError`,`UnsupportedByProtocol`,x6.fromTool),/*#__PURE__*/ PO(x6.fromFeature)),n9=e=>{let t=hCe(e);return c7.make({code:t.code,message:t.message,...sCe(t.data)?{data:t.data}:{}})},r9=/*#__PURE__*/ H(function*(e,t){let n=yield*Fp(lM);return Ni(n)&&_M(n.value,(t,n)=>F(rce(n,e))),yield*t}),gCe=e=>oCe(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta}))),i9=e=>new r6({operation:e,protocolVersion:X5,reason:`MCP 2026-07-28 carries server input requests in multi round-trip results`}),a9=/* @__PURE__ */ E6({protocolVersion:X5,runtime:{_tag:`Stateless`,transport:{jsonRpc:{acceptsBatches:!1},http:{}},profileFromRequestMetadata:lCe},clientRpcs:tCe,clientNotificationRpcs:G7,serverRequestRpcs:nCe,serverNotificationRpcs:rCe,handlerRpcs:/* @__PURE__ */ W7.merge(G7),makeHandlers:(e,t,n)=>{let r=Cx(iCe),i=Cx(D7),a=Cx(O7),o=Cx(k7),s=Cx(A7),c=Cx(j7),l=Cx(M7),u=Cx(K([M7,S7])),d=Cx(F7),f=Cx(N7),p=n.sendNotification,m=p!==void 0,h=n.serverInfo.extensions===void 0?void 0:hte(n.serverInfo.extensions,e=>sn(e)),g=V(n.registrationPresence,e=>{let t={completions:{},logging:{}};return h!==void 0&&(t.extensions=h),e.tools&&(t.tools={listChanged:m}),e.resources&&(t.resources={listChanged:m,subscribe:m}),e.prompts&&(t.prompts={listChanged:m}),{supportedVersions:n.supportedVersions,capabilities:t,serverInfo:n.serverInfo}}),_=i6.useSync(g6),v=H(function*(e){let t=yield*i6,n=e.inputResponses===void 0?void 0:yield*r(e.inputResponses).pipe(yp);return g6(i6.of({...t,inputResponses:n,requestState:e.requestState}))}),y=H(function*(e,t){let n=uCe(e.inputRequests,t);if(Object.keys(n).length!==0)return yield*r9(400,new x6({code:-32021,message:`The request requires client capabilities that were not declared`,data:{requiredCapabilities:n}}))});return{"subscriptions/listen":H(function*(e,{client:t,requestId:r}){if(p===void 0)return yield*new x6({code:-32601,message:`Method not found: subscriptions/listen`});let i=yield*n.registrationPresence,a=yield*Zd(yield*Rp),o=n.getListChangeRevision?.()??0,s=yield*Jd(n.subscribeServerNotifications,a),c={...i.tools&&e.notifications.toolsListChanged===!0?{toolsListChanged:!0}:{},...i.prompts&&e.notifications.promptsListChanged===!0?{promptsListChanged:!0}:{},...i.resources&&e.notifications.resourcesListChanged===!0?{resourcesListChanged:!0}:{},...i.resources&&e.notifications.resourceSubscriptions!==void 0?{resourceSubscriptions:e.notifications.resourceSubscriptions}:{}},l={"io.modelcontextprotocol/subscriptionId":r},u=new Set(c.resourceSubscriptions),d=yield*qC(64),f=yield*Rd();yield*R(function*(){for(;;){let e=yield*EC(s);if(e.listChangeRevision!==void 0&&e.listChangeRevision<=o||e.targetClientId!==void 0&&e.targetClientId!==t.id)continue;let n=e.notification,r=EO(n).pipe(kO({ToolsChanged:()=>c.toolsListChanged===!0?V7:void 0,PromptsChanged:()=>c.promptsListChanged===!0?H7:void 0,ResourcesChanged:()=>c.resourcesListChanged===!0?B7:void 0,ResourceUpdated:e=>u.has(e.uri)?z7:void 0}),FO);if(r===void 0)continue;let i={tag:r._tag,payload:r.payloadSchema.make({_meta:{...n.metadata,...l},...n._tag===`ResourceUpdated`?{uri:n.uri}:{}})};if(!(yield*JC(d,i)))break}}).pipe(wre(a),sp(Qf(()=>n.markSubscriptionCancelled?.(t.id,r)??L)),sp(Ud(f,void 0)),im),yield*p(X5,t.id,{tag:U7._tag,payload:U7.payloadSchema.make({_meta:l,notifications:c})});let m=Qp(sw(d).pipe(B(e=>p(X5,t.id,e))));yield*cie(m,zd(f)),yield*n.terminateSubscription?.(`2026-07-28`,t.id,r,`Pending notification limit exceeded`)??L;let h=yield*K7(n.serverInfo);return L7.make({_meta:{...l,"io.modelcontextprotocol/serverInfo":h},resultType:`complete`})},vp(n9)),"server/discover":H(function*(e){let t=yield*g,r=yield*t9({...e9,supportedVersions:Array.from(t.supportedVersions),capabilities:t.capabilities,instructions:n.serverInfo.instructions},n.serverInfo);return yield*i(r)},vp(n9)),"resources/list":H(function*(t){let r=yield*_,i=yield*e.resources.list(r.protocol),o=yield*t9({...e9,resources:i.map(dCe)},n.serverInfo);return yield*a(o)},vp(n9)),"resources/templates/list":H(function*(t){let r=yield*_,i=yield*e.resources.listTemplates(r.protocol),a=yield*t9({...e9,resourceTemplates:i.map(fCe)},n.serverInfo);return yield*o(a)},vp(n9)),"resources/read":H(function*(t){let r=yield*v(t),i=yield*e.resources.read(t.uri,r),a=i.contents.map(Q7),o=yield*t9({...e9,contents:a,_meta:i._meta},n.serverInfo);return yield*s(o)},vp(n9)),"prompts/list":H(function*(t){if(!(yield*n.registrationPresence).prompts)return yield*r9(404,new x6({code:T3,message:`Method not found`}));let r=yield*_,i=yield*e.prompts.list(r.protocol),a=yield*qf(i,pCe),o=yield*t9({...e9,prompts:a},n.serverInfo);return yield*c(o)},vp(n9)),"prompts/get":H(function*(t){let r=yield*v(t),i=yield*e.prompts.get(t.name,t.arguments??{},r);if(i._tag===`InputRequired`){yield*y(i,r.protocol.clientCapabilities);let e=yield*K7(n.serverInfo);return yield*u(Y7(i,e))}let a=i.value,o=a.messages.map(e=>({role:e.role,content:$7(e.content)})),s=yield*t9({description:a.description,messages:o,_meta:a._meta},n.serverInfo);return yield*l(s)},vp(n9)),"completion/complete":H(function*(t){let r=yield*_,i=yield*e.completions.complete({reference:t.ref.type===`ref/prompt`?{type:`prompt`,name:t.ref.name,title:t.ref.title}:{type:`resourceTemplate`,uriTemplate:t.ref.uri},argument:t.argument,context:t.context?.arguments===void 0?void 0:{arguments:t.context.arguments},metadata:t._meta},r),a=yield*t9({completion:q7({values:Array.from(i.values),total:i.total,hasMore:i.hasMore}),_meta:i.metadata},n.serverInfo);return yield*d(a)},vp(n9)),"tools/list":H(function*(t){let r=yield*_,i=yield*e.tools.list(r.protocol),a=yield*qf(i,mCe),o=yield*t9({...e9,tools:a},n.serverInfo);return yield*f(o)},vp(n9)),"tools/call":H(function*(t){let r=yield*v(t),i=(yield*e.tools.list(r.protocol)).find(e=>e.name===t.name),a=yield*Fp(lM);if(i!==void 0&&Ni(a)){let e=[{schema:i.inputSchema,argument:t.arguments,path:``}];for(;e.length>0;){let{schema:t,argument:n,path:r}=e.pop();if(!sn(t))continue;let i=t[`x-mcp-header`];if(typeof i==`string`){let e=`mcp-param-${i.toLowerCase()}`;if(!cCe(a.value.headers[e],n))return yield*r9(400,new x6({code:O3,message:`${e} does not match argument '${r}'`}))}if(sn(t.properties))for(let[i,a]of Object.entries(t.properties))e.push({schema:a,argument:sn(n)&&Object.hasOwn(n,i)?n[i]:void 0,path:r===``?i:`${r}.${i}`})}}let o=yield*e.tools.call({name:t.name,arguments:t.arguments??{}},r).pipe(mp([`ToolExecutionError`,`InvalidToolInput`],e=>F(c6.Complete(J3.make({content:[B3.make({type:`text`,text:e.message})],isError:!0})))));if(o._tag===`InputRequired`)return yield*y(o,r.protocol.clientCapabilities),yield*Z7(o,n.serverInfo);let s=o.value,c=s.content.map($7);return yield*Z7(c6.Complete({content:c,structuredContent:s.structuredContent,isError:s.isError,_meta:s._meta}),n.serverInfo)},vp(n9)),"notifications/cancelled":H(function*(e){return yield*L})}},toReverseClient:()=>({listRoots:()=>z(i9(`roots/list`)),createMessage:()=>z(i9(`sampling/createMessage`)),elicit:()=>z(i9(`elicitation/create`))}),projectNotification:e=>T6(e)?F(void 0):w6({supportsProgressMessage:!0},e),normalizeCancellation:gCe}),_Ce=bSe,vCe=Xxe,o9=/*#__PURE__*/ new WeakMap,s9=/*#__PURE__*/ _a(`effect/ai/McpServer/RequestNotificationQueue`,{defaultValue:()=>void 0}),c9=e=>e._tag===`Progress`||e._tag===`LoggingMessage`,yCe=/*#__PURE__*/ Xbe.omit(`notifications/elicitation/complete`),l9=/*#__PURE__*/ Sx(X3),bCe=e=>{switch(e.tag){case`notifications/cancelled`:return d6.Cancelled({requestId:e.payload.requestId,reason:e.payload.reason,metadata:e.payload._meta});case`notifications/progress`:return d6.Progress({progressToken:e.payload.progressToken,progress:e.payload.progress,total:e.payload.total,message:e.payload.message,metadata:e.payload._meta});case`notifications/message`:return d6.LoggingMessage({level:e.payload.level,logger:e.payload.logger,data:e.payload.data,metadata:e.payload._meta});case`notifications/resources/updated`:return d6.ResourceUpdated({uri:e.payload.uri,metadata:e.payload._meta});case`notifications/resources/list_changed`:return d6.ResourcesChanged({metadata:e.payload?._meta});case`notifications/tools/list_changed`:return d6.ToolsChanged({metadata:e.payload?._meta});case`notifications/prompts/list_changed`:return d6.PromptsChanged({metadata:e.payload?._meta});default:return}},u9=(e,t)=>{let n=Lp(e,i6,t.requestContext),r=t.requestContext.requestMetadata,i=N(r,`io.modelcontextprotocol/logLevel`)?r[`io.modelcontextprotocol/logLevel`]:void 0;return l9(i)&&(n=Lp(n,Gd,f6[i].effect)),t.serverClient===void 0?n:Lp(n,a6,t.serverClient)};var d9=class e extends (/*#__PURE__*/ P()(`effect/ai/McpServer`)){static make=/*#__PURE__*/ R(function*(){let t=yield*rxe,n=Pa(),r=[],i=[],a=[],o=yield*GC(),s={consumers:0,listChangeRevision:0,requestEndpoints:0},c=()=>s.consumers===0&&s.requestEndpoints>0,l=/* @__PURE__ */ new Map,u=(yield*Eo).makeDispatcher(),d=yield*tN(yCe,{spanPrefix:`McpServer/Notifications`,onFromClient:e=>Rd().pipe(B(t=>ap(n=>{let r=e.message;if(r._tag!==`Request`)return L;let i=bCe(r);if(i===void 0)return L;let a={notification:i,delivered:t,requestContext:ca(n.context,i6),requestHeaders:ca(n.context,lM)?.headers},f=Qf(()=>d.write({clientId:0,requestId:r.id,_tag:`Exit`,exit:Md})),p=da(n.context,s9);if(p!==void 0&&a.requestContext!==void 0&&c9(i))return YC(p,a),sp(zd(t),f);if(c())return f;let m=!1;if(r.tag.includes(`list_changed`)){let e=++s.listChangeRevision,t=l.get(r.tag);t===void 0?(a.listChangeRevision=e,m=!0,l.set(r.tag,a),u.scheduleTask(()=>{l.delete(r.tag),YC(o,a)},0)):t.listChangeRevision=e}else m=!0,YC(o,a);return m&&a.requestContext!==void 0&&s.consumers>0?sp(zd(t),f):f})))}),f=e.of({notifications:d.client,notifyElicitationComplete:({clientId:e,elicitationId:t})=>c()?L:Rd().pipe(B(n=>JC(o,{notification:d6.ElicitationComplete({elicitationId:t}),targetClientId:e,delivered:n}).pipe(sp(Qf(()=>s.consumers>0?zd(n):L))))),get tools(){return n},addTool:e=>R(function*(){let r=n.findIndex(({tool:t})=>t.name===e.tool.name);r===-1?n.push(e):n[r]=e;let i=ca(e.annotations,s6);yield*t.tools.register({descriptor:new q3({...e.tool,title:e.tool.title??e.tool.annotations?.title}),isVisible:e=>i===void 0||i({protocolVersion:e.protocolVersion,capabilities:e.clientCapabilities,clientInfo:e.clientInfo}),handle:(t,n)=>u9(e.handle(t.arguments),n).pipe(rie({InternalError:t=>z(new txe({name:e.tool.name,message:t.message})),InvalidParams:t=>z(new(n.requestContext.requestState===void 0&&n.requestContext.inputResponses===void 0?$be:exe)({name:e.tool.name,message:t.message}))}),V(e=>ln(e,`InputRequired`)?c6.InputRequired(e):c6.Complete(e)))}),yield*d.client[`notifications/tools/list_changed`]({})}),callTool:e=>R(function*(){let n=yield*a6,r=yield*t.tools.call(e,h6(n)).pipe(vp(e=>new M3({message:e._tag===`ToolNotFound`?`Tool '${e.name}' not found`:e.message})));return r._tag===`InputRequired`?yield*new M3({message:`Client input is not supported by this MCP protocol`}):r.value}),get resources(){return r},get resourceTemplates(){return i},addResource:e=>R(function*(){let n=r.findIndex(({resource:t})=>t.uri===e.resource.uri);n===-1?r.push(e):r[n]=e,yield*t.resources.register({descriptor:e.resource,isVisible:t=>{let n=ca(e.annotations,s6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},read:t=>u9(e.handle,t)}),yield*d.client[`notifications/resources/list_changed`]({})}),addResourceTemplate:({annotations:e,completions:n,handle:r,routerPath:a,template:o})=>R(function*(){let s=i.findIndex(({template:e})=>e.uriTemplate===o.uriTemplate);s===-1?i.push({template:o,annotations:e}):i[s]={template:o,annotations:e};let c=OCe();c.add(a,!0),yield*t.resources.registerTemplate({descriptor:o,isVisible:t=>{let n=ca(e,s6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},match:e=>{let t=c.find(e);if(t===void 0)return;let n=[];for(let e of Object.keys(t.params))n[Number(e)]=t.params[e];return n},read:(e,t,n)=>u9(r(e,Array.from(t)),n)});for(let[e,r]of Object.entries(n))yield*t.completions.register(`resource/${o.uriTemplate}/${e}`,(e,t)=>u9(r(e.argument.value,e.context),t).pipe(V(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*d.client[`notifications/resources/list_changed`]({})}),findResource:e=>R(function*(){let n=yield*a6;return yield*t.resources.read(e,h6(n)).pipe(mp(`ResourceNotFound`,e=>z(new M3({message:`Resource '${e.uri}' not found`}))))}),get prompts(){return a},addPrompt:e=>R(function*(){let n=a.findIndex(({prompt:t})=>t.name===e.prompt.name);n===-1?a.push(e):a[n]=e,yield*t.prompts.register({descriptor:e.prompt,isVisible:t=>{let n=ca(e.annotations,s6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},get:(t,n)=>u9(e.handle(t),n).pipe(V(e=>ln(e,`InputRequired`)?c6.InputRequired(e):c6.Complete(e)))});for(let[n,r]of Object.entries(e.completions))yield*t.completions.register(`prompt/${e.prompt.name}/${n}`,(e,t)=>u9(r(e.argument.value,e.context),t).pipe(V(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*d.client[`notifications/prompts/list_changed`]({})}),getPromptResult:H(function*({arguments:e,name:n}){let r=yield*a6,i=yield*t.prompts.get(n,e??{},h6(r)).pipe(mp(`PromptNotFound`,()=>new M3({message:`Prompt '${n}' not found`})));return i._tag===`Complete`?i.value:yield*new M3({message:`Client input is not supported by this MCP protocol`})}),completion:H(function*(e){let n=yield*a6,r=e.ref,i=yield*t.completions.complete({reference:r.type===`ref/resource`?{type:`resourceTemplate`,uriTemplate:r.uri}:{type:`prompt`,name:r.name},argument:e.argument,context:e.context},h6(n));return{_meta:i.metadata,completion:{values:i.values,total:i.total,hasMore:i.hasMore}}})});return o9.set(f,{core:t,notifications:o,notificationDelivery:s}),f});static layer=/*#__PURE__*/ pf(e)(e.make)};const f9=`mcp-session-id`,p9=/*#__PURE__*/ new WeakMap,m9=/*#__PURE__*/ new WeakMap,h9=e=>`${typeof e}:${e}`;var g9=class extends Fo{};const _9=/*#__PURE__*/ H(function*(e,t,n,r){let i=yield*uN,a=yield*d9,o=yield*Gd,s=n===`http`,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map,d=e=>{l.delete(e),c.delete(e),t.disconnect(e)},f=(e,t,n)=>i.send(e,{_tag:`Exit`,requestId:t,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:n}]}}),p=(e,t)=>{let n=u.get(e);if(n===void 0)return;let r=n.filter(e=>e!==t);r.length===0?u.delete(e):u.set(e,r)},m=yield*xC(),h=(e,n,r)=>Qf(()=>{let a=t.selectProtocol(e),o=a.serverNotificationRpcs.requests.get(r.tag);return o===void 0?rp(`MCP protocol ${e} does not define server notification ${r.tag}`):a.payloadCodecs(o).encode(r.payload).pipe(yp,B(e=>i.send(n,{_tag:`Request`,id:``,tag:r.tag,payload:e,headers:[],isNotification:!0})))}),g=(e,t)=>{let n=l.get(e),r=h9(t),i=n?.get(r);return i!==void 0&&(n.set(r,{...i,cancelled:!0}),!0)},_=(e,t,n,r)=>Qf(()=>g(t,n)?s?i.end(t):h(e,t,{tag:`notifications/cancelled`,payload:{requestId:n,reason:r}}):L),v,{core:y,notificationDelivery:b,notifications:x}=o9.get(a),S=r?.handlers??(yield*t.installHandlers({core:y,subscribeServerNotifications:wC(m),getListChangeRevision:()=>b.listChangeRevision,...!i.supportsNotifications||e.allowSubscriptions===!1?{}:{sendNotification:h,markSubscriptionCancelled:(e,t)=>I(()=>{g(e,t)}),terminateSubscription:_},defaultLogLevel:o,serverInfo:e})),ee=yield*ZT({lookup:H(function*(e){let n=t.selectProtocol(e.profile.protocolVersion),r,a=yield*rN.make(H(function*(t){let n=0;return r=e=>t(n,e),{send(t,r,a){if(n=t,r._tag===`Request`){let t=h9(r.id),n=u.get(t)??[];return n.push(e),u.set(t,n),i.send(e.clientId,{_tag:`Request`,id:r.id,tag:r.tag,payload:r.payload,headers:[]}).pipe(Up(()=>I(()=>p(t,e))))}return r._tag===`Interrupt`?(p(h9(r.requestId),e),h(e.profile.protocolVersion,e.clientId,{tag:`notifications/cancelled`,payload:{requestId:r.requestId}})):L},supportsAck:!0,supportsTransferables:!1,supportsStructuredClone:!1,codecFor:i.codecFor}}));return{client:yield*n.makeReverseClient(e.profile).pipe(Lp(rN,a)),write:r}}),idleTimeToLive:1e4}),C=o6.of((e,{client:n,headers:r,payload:i,rpc:a})=>{let s=t.resolveRequest(n.id,r);if(!a._tag.endsWith(`/initialize`)&&!s){let e=QS(),t=ca(e.context,lM);return t&&_M(t,()=>F(aj({status:r[f9]===void 0?400:404}))),rp(/* @__PURE__ */ Error(`Mcp-Session-Id does not exist`))}let l=s?.initializePayload??i,u=c.get(n.id),d=s?.protocol??u?.protocol??t.protocolForInternalTag(a._tag);if(!kCe(d.protocolVersion)||d.protocolVersion===`2026-07-28`)return rp(`Unsupported selected MCP protocol version: ${d.protocolVersion}`);let f=s?.negotiatedProfile??{protocolVersion:d.protocolVersion,clientCapabilities:l.capabilities,clientInfo:l.clientInfo};u!==void 0&&(u.profile=f);let p=i6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,requestMetadata:l._meta});return Lp(Lp(Lp(e,a6,a6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,initializePayload:l,requestMetadata:sn(i)&&sn(i._meta)?i._meta:void 0,getClient:QT(ee,new g9({clientId:n.id,profile:f})).pipe(V(({client:e})=>e))})),i6,p),Gd,t.effectLogLevel(n.id,r,o))}),te=uN.of({...i,send:(e,t)=>{if(t._tag===`Exit`){let r=l.get(e),a=h9(t.requestId),o=r?.get(a);if(r!==void 0&&r.delete(a)&&r.size===0&&l.delete(e),o?.cancelled===!0)return n===`custom`?L:(o.httpPost!==void 0&&o.httpPost.expected--,p9.set(t,t.requestId),i.send(e,t));if(t.exit._tag===`Failure`&&!t.exit.cause.some(e=>e._tag===`Fail`))return i.send(e,{_tag:`Exit`,requestId:t.requestId,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:new N3({message:`Internal error`})}]}})}return i.send(e,t)},run:e=>(v=e,i.run((n,r)=>{let i=QS(),a=r,o=s?ca(i.context,lM):void 0;switch(o!==void 0&&a._tag!==`Eof`&&_M(o,(e,t)=>F(t.status===200&&t.body._tag===`Uint8Array`&&t.body.contentLength===0?aj({headers:bg(t.headers,`content-type`),status:202}):t)),a._tag){case`Request`:{if(o!==void 0&&a.isNotification!==!0){let e=m9.get(o)??{expected:0};e.expected++,m9.set(o,e)}let r=s?ua(QS().context,lM).headers:hg(a.headers),u=a.tag===`notifications/cancelled`&&typeof a.payload==`object`&&a.payload!==null&&`requestId`in a.payload&&(typeof a.payload.requestId==`string`||typeof a.payload.requestId==`number`)?l.get(n)?.get(h9(a.payload.requestId)):void 0,p=u===void 0?t.prepareRequest(n,r,a):F(u.prepared);return R(function*(){let u=yield*p,m=c.get(n);s&&m===void 0&&(yield*Xd(ua(i.context,Kd),I(()=>d(n))));let h=u.binding,_=u.protocol;if(c.set(n,{protocol:_,profile:u.profile??m?.profile,sessionHeaders:s&&r[f9]!==void 0?hg({[f9]:r[f9]}):m?.sessionHeaders}),a.tag===`invalid/json-rpc-batch`)return yield*f(n,a.id,new A3({message:`JSON-RPC batches are not supported`}));o!==void 0&&h!==void 0&&_M(o,(e,i)=>F(t.resolveRequest(n,r)===void 0?aj({status:404}):pj(i,`mcp-protocol-version`,h.protocol.protocolVersion)));let v=t.routeClientRequest(_,a),y=t.clientRpcs.requests.get(v.tag),b=_.clientNotificationRpcs.requests.has(a.tag);if(y&&b&&a.isNotification){if(!h&&_.runtime._tag===`Stateful`){o&&_M(o,()=>F(aj({status:r[f9]===void 0?400:404})));return}let t=_.payloadCodecs(y).decode(a.payload);return yield*R(function*(){let i=yield*t;if(a.tag===`notifications/cancelled`){let t=yield*_.normalizeCancellation(i),r=h9(t.requestId),a=n;if(s){if(h===void 0)return;let e=Array.from(l).find(([,e])=>e.get(r)?.prepared.binding===h);if(e===void 0)return;a=e[0]}return g(a,t.requestId)?yield*e(a,{_tag:`Interrupt`,requestId:t.requestId}):void 0}let o=S.mapUnsafe.get(y.key),c=o?o.handler(i,{rpc:y,requestId:KM(a.id),client:new VM(n),headers:r}):L;return yield*u.requestContext===void 0?c:Lp(c,i6,u.requestContext)}).pipe(Cp)}if(!y||b)return a.isNotification?void 0:yield*f(n,a.id,new j3({message:`Method not found: ${a.tag}`}));let x=yield*lp(_.payloadCodecs(y).decode(a.payload));if(Ca(x))return yield*a.isNotification?L:f(n,a.id,new M3({message:`Invalid method parameters`}));if(a.isNotification!==!0){let e=l.get(n)??/* @__PURE__ */ new Map;e.set(h9(a.id),{requestId:KM(a.id),prepared:u,cancelled:!1,httpPost:o===void 0?void 0:m9.get(o)}),l.set(n,e)}let ee=e(n,v);return yield*u.requestContext===void 0?ee:Lp(ee,i6,u.requestContext)}).pipe(pp(e=>a.isNotification?L:f(n,a.id,ln(e,`ProtocolError`)?x6.fromFeature(e):new M3({message:`Invalid request metadata`}))))}case`Ping`:case`Ack`:case`Interrupt`:return e(n,a);case`Eof`:return s||d(n),e(n,a);case`Pong`:case`Exit`:case`Chunk`:case`ClientProtocolError`:case`Defect`:{let e=a._tag===`Exit`?h9(a.requestId):void 0,r=s?t.resolveRequest(n,ua(QS().context,lM).headers):void 0,i=(e===void 0?void 0:u.get(e))?.find(e=>s?e.profile===r?.negotiatedProfile:e.clientId===n);if(a._tag===`Exit`&&i===void 0)return L;i!==void 0&&e!==void 0&&p(e,i);let o=i?.clientId??n,l=c.get(o),d=l?.protocol??t.protocols[0],f=i?.profile??l?.profile??{protocolVersion:d.protocolVersion,clientCapabilities:{},clientInfo:{name:`unknown`,version:`unknown`}};return QT(ee,new g9({clientId:o,profile:f})).pipe(B(({write:e})=>e(a)),zp)}}}))});s&&(yield*t.onSessionTerminated(e=>{let t=[];for(let[n,r]of l)for(let{prepared:i,requestId:a}of r.values())i.binding===e&&g(n,a)&&t.push(v(n,{_tag:`Interrupt`,requestId:a}));return Kf(t,{discard:!0})})),r===void 0&&(yield*Bp(I(()=>{b.consumers++}),()=>I(()=>{b.consumers--})));let w=/* @__PURE__ */ new Map;return yield*sw(r?.notifications??x).pipe(B(H(function*(e){let{delivered:n,listChangeRevision:r,notification:i,targetClientId:a,requestContext:l,requestHeaders:u}=e;T6(i)&&(yield*CC(m,{notification:i,targetClientId:a,listChangeRevision:r}));let d=yield*te.clientIds;for(let e of c.keys())d.has(e)||(c.delete(e),t.disconnect(e));let f=c9(i),p=f&&l!==void 0?[l.clientId]:a===void 0?s?c.keys():t.deliveryClientIds():[a],h=[],g=!1;for(let e of p){if(a!==void 0&&e!==a)continue;if(!d.has(e)){t.disconnect(e);continue}if(!te.supportsNotifications)continue;let r=f&&l!==void 0?t.selectProtocol(l.protocolVersion):c.get(e)?.protocol;if(!r)continue;let s=w.get(e),p=e===(a??l?.clientId);g||=p;let m=p?n:Ld();w.set(e,m);let _=R(function*(){s!==void 0&&(yield*zd(s));let n=yield*r.projectNotification(i);if(n===void 0||i._tag===`Progress`&&r.runtime._tag===`Stateless`&&l?.requestMetadata?.progressToken!==i.progressToken)return;if(i._tag===`LoggingMessage`&&r.runtime._tag===`Stateless`){let t=l?.requestMetadata,n=N(t,`io.modelcontextprotocol/logLevel`)?t[`io.modelcontextprotocol/logLevel`]:void 0;if(l?.clientId!==e||!l9(n)||X3.literals.indexOf(i.level)<X3.literals.indexOf(n))return}else if(!t.canDeliver(e,(l?.clientId===e?u:void 0)??c.get(e)?.sessionHeaders??mg,i,o))return;let a=r.serverNotificationRpcs.requests.get(n.tag);if(!a)return;let d=yield*r.payloadCodecs(a).encode(n.payload);yield*te.send(e,{_tag:`Request`,id:``,tag:n.tag,payload:d,headers:[],isNotification:!0})}).pipe(Cp,Hp(I(()=>{Wd(m,Md),w.get(e)===m&&w.delete(e)})));h.push(_)}g||(yield*Ud(n,void 0)),yield*Kf(h,{concurrency:`unbounded`,discard:!0}).pipe(im({startImmediately:!0}))})),Cp,Qp,im),yield*Ule(t.clientRpcs,{spanPrefix:`McpServer`,disableFatalDefects:!0}).pipe(Lp(uN,te),Lp(o6,C),Mp(S))},zp),xCe=(e,t)=>gf(R(function*(){let n=yield*z6;yield*im(_9(e,n,t))})).pipe(wf(d9.layer)),SCe=e=>{let t=V6(e.protocols);return xCe(e,`http`).pipe(Cf(wCe(e)),Cf(t),Cf(Mle()))},CCe=e=>gf(R(function*(){let t=yield*z6,n=t.protocols.find(e=>e.runtime._tag===`Stateful`);if(n!==void 0)return yield*new Cd(`McpServer.layerHttpRequestScoped does not support the sessionful MCP protocol ${n.protocolVersion}`);let r=yield*d9,{core:i,notificationDelivery:a}=o9.get(r),o=yield*t.installHandlers({core:i,subscribeServerNotifications:rp(`Subscriptions are disabled for request-scoped MCP servers`),getListChangeRevision:()=>a.listChangeRevision,defaultLogLevel:yield*Gd,serverInfo:e});yield*Bp(I(()=>{a.requestEndpoints++}),()=>I(()=>{a.requestEndpoints--})),yield*v9(e,R(function*(){let{httpEffect:n,protocol:i}=yield*dN().pipe(Lp(XM,y9)),a=yield*GC();return yield*_9(e,t,`http`,{notifications:a,handlers:o}).pipe(Lp(uN,i),Lp(d9,r),im({startImmediately:!0})),yield*Lp(n,s9,a)}))})).pipe(wf(d9.layer),Cf(V6(e.protocols))),wCe=e=>pf(uN)(R(function*(){let{httpEffect:t,protocol:n}=yield*dN().pipe(Lp(XM,y9));return yield*v9(e,t),n})),v9=/*#__PURE__*/ H(function*(e,t){let n=yield*z6,r=yield*yM,i=e.allowSessionTermination===!0&&n.protocols.some(e=>e.runtime._tag===`Stateful`),a=F(aj({status:403})),o=t=>n=>x9(n,e.allowedOrigins)?t(n):a,s=F(aj({status:405,headers:{allow:i?`POST, DELETE`:`POST`}})),c=o(()=>s);for(let t of[`GET`,`PUT`,`PATCH`,`OPTIONS`])yield*r.add(t,e.path,c);yield*r.add(`DELETE`,e.path,i?o(e=>n.terminateHttpSession(e.headers)):c),yield*r.add(`POST`,e.path,r=>{if(!x9(r,e.allowedOrigins))return F(aj({status:403}));if(S9(r.headers[`content-type`])[0]!==`application/json`)return F(aj({status:415}));let i=S9(r.headers.accept);return!i.includes(`application/json`)||!i.includes(`text/event-stream`)?F(aj({status:406})):R(function*(){let e=yield*lp(B(r.text,wx(Qoe))),i=n.admitHttp(r.headers,e);if(i._tag===`Rejected`)return i.response;let a=e=>{let t=e.body._tag===`Uint8Array`&&e.body.body.subarray(0,-1).includes(10);return i.isSubscription||e.body._tag===`Stream`||t?DCe(e,i.isSubscription):e};return i.acknowledge?yield*hp(V(t,a),()=>F(aj({status:202}))):yield*B(t,e=>e.body._tag!==`Uint8Array`||e.body.body.length>0?F(a(e)):m9.get(r)?.expected===0?F(fj(xE,{contentType:`text/event-stream`})):rp(/* @__PURE__ */ Error(`MCP request ended without writing its response`)))})})}),y9=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ECe();return XM.of({contentType:e.contentType,includesFraming:!0,codecFor:e.codecFor,makeUnsafe:()=>{let t=e.makeUnsafe();return{decode:t.decode,encode:e=>{let n=t.encode(e);return typeof n==`string`?`${n}\n`:n}}}})})(),TCe=/*#__PURE__*/ Sx(/*#__PURE__*/ nS(`Cause`,{data:/*#__PURE__*/ Foe([/*#__PURE__*/ nS(`Fail`,{error:/*#__PURE__*/ joe(P3)})])})),b9=e=>Array.isArray(e)?e.map(b9):!sn(e)||!N(e,`error`)?e:TCe(e.error)?{...e,error:e.error.data[0].error}:e;function ECe(e){let t=ZM(e);return XM.of({...t,makeUnsafe:()=>{let e=t.makeUnsafe(),n=/* @__PURE__ */ new Set;return{decode:e.decode,encode:t=>{if(sn(t)){let e=p9.get(t);e!==void 0&&(p9.delete(t),n.add(e))}let r=e.encode(t);if(typeof r!=`string`||n.size===0&&!r.includes(`"_tag":"Cause"`))return r;let i=JSON.parse(r);if(n.size>0){let e=e=>!(sn(e)&&!N(e,`method`)&&(typeof e.id==`string`||typeof e.id==`number`)&&n.delete(e.id));if(Array.isArray(i)){let t=i.filter(e);if(t.length===0)return;i=t}else if(!e(i))return}return JSON.stringify(b9(i))}}}})}const DCe=(e,t)=>{let n=new TextEncoder,r=new TextDecoder,i=e=>n.encode(r.decode(e).trimEnd().split(`
|
|
535
|
+
`).map(e=>`data: ${e}\n\n`).join(``)),a={status:e.status,statusText:e.statusText,headers:bg(e.headers,`content-type`),cookies:e.cookies,contentType:`text/event-stream`};if(e.body._tag===`Stream`){let r=e.body.stream.pipe(OE(i));if(!t)return fj(r,a);let o=gE(`15 seconds`).pipe(LE(1),OE(()=>n.encode(`: keepalive
|
|
536
|
+
|
|
537
|
+
`)));return fj(NE(r,o,{haltStrategy:`left`}),a)}return e.body._tag===`Uint8Array`?sj(i(e.body.body),a):pj(e,`content-type`,`text/event-stream`)},x9=(e,t)=>{let n=e.headers.origin;return n===void 0||(t??[]).includes(n)},S9=e=>e===void 0?[]:e.split(`,`).flatMap(e=>{let[t,...n]=e.split(`;`),r=n.map(e=>e.trim().toLowerCase()).find(e=>e.startsWith(`q=`));if(r!==void 0){let e=Number(r.slice(2));if(!Number.isFinite(e)||e<=0||e>1)return[]}return[t.trim().toLowerCase()]}),OCe=()=>{let e=QA({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(t,n)=>{e.on(`GET`,`/${t}`,n)},find:t=>e.find(`GET`,`/${t}`)}},kCe=e=>e===`2024-11-05`||e===`2025-03-26`||e===`2025-06-18`||e===`2025-11-25`||e===`2026-07-28`,C9=a9,ACe=[a9,_Ce,vCe],jCe=Sx(tL),MCe=Sx(G(tL)),w9=e=>rL(MI(e)),T9=e=>{let t=MI(e),n=rL(t);if(n!==void 0)return{kind:n,many:!1};if(!Cv(t)||t.encoding!==void 0)return;let[r,...i]=new Set([...t.elements,...t.rest].map(w9));return r===void 0||i.length>0?void 0:{kind:r,many:!0}},NCe=e=>{let t=e.context?.isOptional===!0,n=MI(e);if(t&&Tv(n)&&n.types.length===2){let[e,...t]=n.types.filter(e=>!Fie(e)),r=e===void 0||t.length>0?void 0:w9(e);return r===void 0?void 0:{kind:r,many:!1}}let r=T9(n);return r===void 0||t&&r.many?void 0:r},E9=e=>{let t=MI(e.ast),n=T9(t);if(n!==void 0)return{fields:[{name:void 0,...n}],rest:void 0};if(!wv(t)||t.encoding!==void 0)return{fields:[],rest:e};let r=t.propertySignatures.flatMap(({name:e,type:t})=>{let n=NCe(t);return n===void 0?[]:[{name:String(e),...n}]});if(r.length===0)return{fields:r,rest:e};let i=new Set(r.map(({name:e})=>e)),a=t.propertySignatures.filter(({name:e})=>!i.has(e)),{identifier:o,...s}=t.annotations??{};return{fields:r,rest:a.length===0&&t.indexSignatures.length===0?void 0:Ax(new $v(a,t.indexSignatures,s))}},PCe=e=>[...yv(e)?e.typeParameters:[],...Cv(e)?[...e.elements,...e.rest]:[],...wv(e)?[...e.propertySignatures,...e.indexSignatures].map(({type:e})=>e):[],...Tv(e)?e.types:[],...Ev(e)?[e.thunk()]:[],...(e.encoding??[]).map(({to:e})=>e)],FCe=e=>{let t=/* @__PURE__ */ new Set,n=[e];for(let e=n.pop();e!==void 0;e=n.pop())if(!t.has(e)){if(t.add(e),nL(e))return!0;n.push(...PCe(e))}return!1},ICe=(e,{rest:t})=>[e.input,...e.error,...t===void 0?[]:[t]].some(({ast:e})=>FCe(e)),LCe=(e,t)=>e.fields.flatMap(({name:e,kind:n,many:r})=>{let i=e===void 0?t:N(t,e)?t[e]:void 0;return(r?MCe(i)?i:[]:jCe(i)?[i]:[]).map(t=>({kind:n,field:e,value:t}))}),RCe=Sx(G3),D9=(e,t)=>{let n=WS(e,{onExcessProperty:t?`error`:`ignore`}),[r,i]=Jt(n.schema.$ref)?Rb(n.schema.$ref)??[]:[],a=r===`$defs`&&i!==void 0?n.definitions[i]:n.schema;return a===void 0||Object.keys(n.definitions).length===0?a:{...a,$defs:n.definitions}},zCe=e=>{let t=e.map(([e])=>e).filter(e=>!RCe(D9(GS(e.input),!0))).map(({name:e})=>e);if(t.length>0)throw Error(`MCP tool input must be one object with keys, such as a struct: ${t.join(`, `)} (wrap a union, an array or a scalar in a field, omit input for no arguments, or leave the action out of actions)`);let n=e.filter(([e,t])=>ICe(e,t)).map(([{name:e}])=>e);if(n.length>0)throw Error(`MCP media must be the success or an array of it, or a top-level field of a struct success, one, optional or a required array: ${n.join(`, `)} (make the image such a field, or give an optional array as a required one, empty when absent; an image in input or an error is not served over MCP, so leave that action out of actions)`)},BCe=e=>new J3({isError:!0,content:[{type:`text`,text:e}]}),O9=e=>e===void 0?[]:[{type:`text`,text:JSON.stringify(e)}],VCe=({kind:e,field:t,value:n})=>({type:e,data:n.data,mimeType:n.mimeType,...t===void 0?{}:{_meta:{"effect-actions/field":t}}}),HCe=(e,t)=>V(Cx(G3)(D9(GS(e.input),!0)),n=>new q3({name:e.name,description:e.description,inputSchema:n,outputSchema:t,annotations:{...e.mcp.title===void 0?{}:{title:e.mcp.title},...wbe(e)},_meta:e.mcp._meta===void 0?void 0:{...e.mcp._meta}})),UCe=H(function*(e,t){let n=yield*d9,r=yield*QI(e),i=yield*Ap(),a=e=>mm(e).pipe(sp(iO(e)),dp(BCe(`Tool execution failed due to an internal server error.`))),o=e=>vd(e)?a(e):tp(e);for(let[e,a]of r){let r=E9(e.success),s=r.fields.length===0?void 0:r,c=s===void 0?GS(e.success):s.rest===void 0?void 0:GS(s.rest),l=c===void 0?void 0:yield*Cx(K3)(D9(c,!1)).pipe(yp),u=yield*HCe(e,l).pipe(yp),d=Cx(GS(e.input),$I),f=e=>{let t=Ex(GS(e));return e=>yp(t(e))},p=f(e.success),m=f(K(BI(e))),h=t===void 0||e.caller===yI?a:e=>MB(hfe(t,a(e))),g=new Set(s?.fields.map(({name:e})=>e)),_=(e,t)=>{if(s===void 0)return new J3({isError:!1,structuredContent:e,content:O9(e)});let n=LCe(s,t).map(VCe);if(c===void 0)return new J3({isError:!1,content:n});let r=on(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!g.has(e))):e;return new J3({isError:!1,structuredContent:r,content:[...O9(r),...n]})};yield*n.addTool({tool:u,annotations:ia(),handle:t=>mie({tool:e.name,parameters:t??{}}).pipe(sp(()=>d(t??{})),vp(({message:t})=>new M3({message:new Tbe({toolName:e.name,description:t}).message})),B(e=>h(e).pipe(kp({onFailure:e=>V(m(e),e=>new J3({isError:!0,content:O9(e)})),onSuccess:e=>V(p(e),t=>_(t,e))}))),hp(o),Ip(e=>ha(i,e)))})}}),WCe=(e,t,n=ff,r)=>{jI(`MCP tool`,e.flatMap(e=>e.actions),AI);let i=e.flatMap(e=>e.actions.map(e=>[e,E9(e.success)]));zCe(i);let a=new Set(i.map(([{name:e}])=>e)),o=R(function*(){let t=(yield*d9).tools.flatMap(({tool:e})=>a.has(e.name)?[e.name]:[]);if(t.length>0)return yield*rp(/* @__PURE__ */ Error(`Duplicate MCP tool: ${t.join(`, `)}, claimed by an action and a native feature (rename the native tool, or leave the action out of actions)`));yield*UCe(e,r)});return gf(o).pipe(Cf(n),Cf(t),Mre,ZI(e))},GCe=/* @__PURE__ */ new Set([`server/discover`,`tools/list`,`notifications/cancelled`]),KCe=e=>{let t=new Set(e.filter(({caller:e})=>e===yI).flatMap(({name:e})=>[e,`=?base64?${vh(e)}?=`]));return e=>{if(t.size===0||e[`mcp-protocol-version`]!==C9.protocolVersion)return!0;let n=e[`mcp-method`];if(n===void 0)return!0;if(GCe.has(n))return!1;if(n!==`tools/call`)return!0;let r=e[`mcp-name`];return r===void 0||!t.has(r)}},qCe=e=>Dp(e.json,{onFailure:()=>!0,onSuccess:t=>!N(t,`method`)||t.method===e.headers[`mcp-method`]});function JCe(e,{actions:t,features:n,path:r=`/mcp`,authentication:i,requestScoped:a,allowSubscriptions:o=n!==void 0,...s}){let c=XI(KI(e),t),l=c.flatMap(e=>e.actions);bI(l,i);let u=WCe(c,a===!0?CCe({...s,path:r,protocols:[C9]}):SCe({...s,path:r,protocols:ACe,allowSessionTermination:!0,allowSubscriptions:o}),n,i);if(i===void 0)return u;let d=KCe(l),f=OM(V(cL(i),e=>t=>B(lM,n=>n.method!==`POST`||d(n.headers)?e.http(t,!1):B(qCe(n),n=>e.http(t,n)))));return u.pipe(Cf(f.layer))}var YCe=`0.27.0`;const XCe=(e,t)=>Xf(()=>VW({key:e,data:t})),ZCe=(e,t)=>Xf(()=>HW({key:e,data:t})),QCe=async(e,t)=>(await Promise.all([YG(e.authCookies.sessionToken.name,t,e.secret),YG(e.authCookies.dontRememberToken.name,`true`,e.secret)])).map(e=>e.split(`;`)[0]).join(`; `),$Ce=(e,t)=>um(`OwnerAccount.providerSession`)(function*(n){let r=new Date((yield*Ef)+6e4),i=yield*Bp(V4(()=>e.internalAdapter.createSession(n,!0,{expiresAt:r},!0)),t=>Yf(()=>e.internalAdapter.deleteSession(t.token))),a=yield*V4(()=>QCe(e,i.token));return new Headers({origin:t,cookie:a})}),ewe=iH(W({id:U}));var k9=class e extends P()(`clankerauth/OwnerAccount`){static layer=pf(e,R(function*(){let{sql:e}=yield*cH,{auth:t,context:n}=yield*r3,{baseURL:r}=yield*Y4,i=yield*Aw(1),a=$Ce(n,r),o=um(`OwnerAccount.find`)(function*(){let t=yield*e`SELECT id FROM user LIMIT 1`;if(t.length)return(yield*ewe(t[0])).id});return{find:o,create:um(`OwnerAccount.create`)(function*(e){if(yield*o())return yield*z(iV.of());let{headers:n}=yield*V4(()=>t.api.signUpEmail({body:{name:`Owner`,email:e.email.trim(),password:e.password},returnHeaders:!0}),{refused:z4,conflict:iV.of});return n.getSetCookie()},e=>i.withPermit(e)),caller:(e,t,n)=>({userId:e,email:t,writable:n,providerHeaders:a(e)})}}))},A9=class extends P()(`clankerauth/ResponseCookies`){};const twe=V(k9,e=>({setupStatus:()=>e.find().pipe(V(e=>({required:!e}))),setupOwner:um(`Administration.setup`)(function*(t){let n=yield*e.create(t);return yield*(yield*A9).add(n),{created:!0}})}));var j9=class extends Bo(`Unauthorized`){constructor(e={}){super({message:e.message??`Authentication required`}),Object.defineProperty(this,"cause",{value:e.cause})}},M9=class extends US()(`ProviderUnavailable`,{operation:U},{httpApiStatus:503}){constructor(e){super({operation:e.operation}),Object.defineProperty(this,"cause",{value:e.cause})}},N9=class extends Bo(`InsufficientScope`){},nwe=class extends US()(`ConfigurationError`,{message:U}){};const P9=po(1),F9=(e,t)=>jp(n=>Ase(e).execute(t).pipe(Lp(AN,{...ca(n,AN),redirect:`manual`}),vp(e=>new M9({operation:`http.request`,cause:e})),lie(e=>e.status<300||e.status>=400,e=>new M9({operation:`http.redirect`,cause:{status:e.status}})))),rwe=W({keys:G(W({kty:U,crv:Mx(U),x:Mx(U),kid:Mx(U),alg:Mx(U),use:Mx(U),key_ops:Mx(G(U))}))}),iwe=W({sub:_S,client_id:_S,scope:U,iat:cS,exp:cS}),awe=W({list:U}),owe=Gde.pipe(Wx({exp:cS})),swe=()=>({jwks:/* @__PURE__ */ new Map,keyLists:/* @__PURE__ */ new Map}),I9=e=>new j9({cause:e}),cwe=po(1),L9=fo(5),R9=fo(3),z9=e=>t=>wp(t,{duration:R9,orElse:()=>z(new M9({operation:e}))}),B9=um(`Verifier.make`)(function*(e){let t=yield*FA,n=JSON.stringify([e.issuer,e.resource]),r=yield*ip({try:()=>({jwks:new URL(`${e.issuer}/jwks`).href,keyList:new URL(`/api/keyList`,e.issuer).href}),catch:()=>new nwe({message:`Invalid issuer URL`})}),i=um(`Verifier.jwks`)(function*(){let e=yield*F9(t,ase(r.jwks));return e.status===200?(yield*EA(rwe)(e).pipe(vp(e=>new M9({operation:`jwks.decode`,cause:e})))).keys.map(({key_ops:e,...t})=>e?{...t,key_ops:[...e]}:t):yield*new M9({operation:`jwks.fetch`,cause:{status:e.status}})},zp),a=R(function*(){let t=e.store.jwks.get(e.issuer),n=yield*Ef;if(t!==void 0){let e=`keys`in t?cwe:L9;if(n-t.readAt<_o(e))return`keys`in t?t.keys:yield*new M9({operation:t.failure})}let r=yield*lp(i()),a=yield*Ef;return wa(r)?(e.store.jwks.set(e.issuer,{readAt:a,keys:r.success}),r.success):((e.store.jwks.get(e.issuer)?.readAt??-1/0)>=n||e.store.jwks.set(e.issuer,{readAt:a,failure:r.failure.operation}),yield*r.failure)}),o=um(`Verifier.signingKey`)(function*(e,t){let n={keys:[...yield*t]};return yield*Xf({try:()=>cI(n)({alg:`EdDSA`,kid:e}),catch:I9})}),s=um(`Verifier.signed`)(function*(t,n,r=a){let i=yield*ip({try:()=>pI(t),catch:I9});if(i.alg!==`EdDSA`||i.kid===void 0)return yield*I9();let s=yield*o(i.kid,r),c=yield*Ef,{payload:l}=yield*Xf({try:()=>$F(t,s,{issuer:e.issuer,audience:e.resource,algorithms:[`EdDSA`],typ:n,currentDate:new Date(c)}),catch:I9});return l}),c=um(`Verifier.jwt`)(function*(e){let t=yield*s(e,`at+jwt`);if(t.cnf!==void 0)return yield*I9();let n=yield*Cx(iwe)(t).pipe(vp(I9));return{subject:n.sub,scopes:n.scope.split(` `).filter(Boolean),actor:{kind:`client`,clientId:n.client_id},expiresAt:n.exp*1e3}}),l=um(`Verifier.keyList`)(function*(){let n=bA(r.keyList).pipe(wA({resource:e.resource})),i=R(function*(){let e=yield*F9(t,n);return e.status===200?yield*EA(awe)(e).pipe(vp(e=>new M9({operation:`key-list.decode`,cause:e}))):yield*new M9({operation:`key-list.fetch`,cause:{status:e.status}})}),o=yield*im(a.pipe(z9(`jwks.timeout`))),{list:c}=yield*i.pipe(z9(`key-list.timeout`)),l=e=>new M9({operation:`key-list.verify`,cause:e}),u=yield*s(c,hI,XS(o)).pipe(mp(`Unauthorized`,e=>z(l(e)))),d=yield*Cx(owe)(u).pipe(vp(l));return{readAt:yield*Ef,expiresAt:d.exp*1e3,entries:new Map(d.keys.map(e=>[e.id,e.sealed]))}},zp),u=R(function*(){let t=e.store.keyLists.get(n),r=yield*Ef;if(t!==void 0&&r-t.readAt<_o(L9))return t.failure===void 0?void 0:yield*new M9({operation:t.failure});let i=yield*lp(l()),a=yield*Ef,o=e.store.keyLists.get(n),s=o?.failure!==void 0;if(wa(i)){e.store.keyLists.set(n,{readAt:a,failure:void 0,held:i.success}),s&&(yield*hm(`clankerauth key list reads have recovered`));return}if((o?.readAt??-1/0)>=r)return yield*i.failure;let{operation:c}=i.failure;return e.store.keyLists.set(n,{readAt:a,failure:c,held:o?.held}),s||(yield*pm(`clankerauth key list reads are failing; a held list decides until it expires`,{operation:c})),yield*i.failure}),d=R(function*(){let t=yield*lp(u),r=e.store.keyLists.get(n)?.held;return r!==void 0&&r.expiresAt>(yield*Ef)?r:yield*Ca(t)?t.failure:new M9({operation:`key-list.expired`})}),f=um(`Verifier.apiKey`)(function*(t){let r=n=>Xf({try:()=>Jde(t,e.resource,n.entries),catch:I9}),i=yield*Ef,a=e.store.keyLists.get(n)?.held,o=a!==void 0&&i-a.readAt<_o(P9)&&a.expiresAt>i?a:yield*d,s=(yield*r(o))??(yield*B(d,e=>e===o?F(void 0):r(e)));return s===void 0||s.expiresAt!==null&&s.expiresAt<=(yield*Ef)?yield*I9():{subject:s.ownerId,scopes:s.scopes,actor:{kind:`key`,keyId:s.keyId},expiresAt:s.expiresAt??void 0}});return{verifyToken:um(`Verifier.verifyToken`)(function*(t){let n=yield*t.startsWith(`clankerauth_`)?e.apiKeys===!1?z(I9()):f(t):c(t),r=e.requiredScopes?.find(e=>!n.scopes.includes(e));return r===void 0?n:yield*new N9({scope:r,actor:n.actor})})}}),lwe=um(`AdministrationResource.make`)(function*(){let{auth:e}=yield*r3,{baseURL:t}=yield*Y4,n=`${t}/api/auth`,r=fV(t);return{protectedResource:{resource:r,authorizationServers:[n],scopesSupported:[pV.read,pV.write,...Z4],scopesRequired:[pV.read,pV.write]},verifier:yield*B9({issuer:n,resource:r,store:swe(),apiKeys:!1}).pipe(Mp(jN.pipe(Cf(uf(kN,(t,n)=>{let r=new Request(t,n);return r.headers.set(P4,`127.0.0.1`),e.handler(r)})))))}});aL(`whoami`,{description:`The verified subject, issuer and scopes behind this request's credential.`,readOnly:!0,caller:class extends P()(`@clankerauth/CurrentPrincipal`){},success:W({subject:_S,issuer:_S,scopes:G(U)})});const V9=(e,t)=>{let n=`Requires ${e}.`;return t.kind===`client`?new TI({message:n,scopes:[e]}):new TI({message:n})},uwe=(e,t)=>t===void 0||e.scopes.includes(t)?void 0:V9(t,e.actor),H9=e=>e instanceof j9?new CI({message:e.message}):e instanceof N9?V9(e.scope,e.actor):e,U9=(e,t)=>vp(e.verifyToken(cg(t)),H9);um(`Resource.layer`)(function*(e,{scopes:t,required:n},r){let i=new URL(`/`,r.publicUrl).href,a={resource:i,authorizationServers:[r.issuer],scopesSupported:t,scopesRequired:[n]},o=r.discovery===!1?void 0:a,s=yield*B9({issuer:r.issuer,resource:i,store:r.store,requiredScopes:[n],apiKeys:r.apiKeys}),c=e=>wp(e,{duration:`5 seconds`,orElse:()=>z(new M9({operation:`verify.timeout`}))}),l={verifyToken:e=>c(s.verifyToken(e))},u=um(`Resource.principal`)(function*(e,t){let n=FB(e);if(Mi(n))return yield*new CI({message:`A bearer token is required.`});let r=yield*U9(l,n.value),i=uwe(r,t);return i===void 0?r:yield*i}),d=um(`Resource.admit`)(function*(t,n){let r=yield*lp(u(t,n));if(wa(r))return{ok:!0,principal:r.success};let i=ace(HB(r.failure,{authentication:e,protectedResource:o,authorization:t}));return{ok:!1,refusal:{status:i.status,headers:Object.fromEntries(i.headers),body:yield*Yf(()=>i.text())}}});return{resource:i,issuer:r.issuer,protectedResource:o,verifier:l,admit:d,watch:(e,t)=>Qp(R(function*(){let n=yield*u(e,t),r=yield*Ef,i=Math.max(0,(n.expiresAt??1/0)-r);return n.actor.kind===`key`?yield*Tp(Math.min(i,_o(P9))):(yield*Tp(i),yield*H9(new j9))}))}});const dwe=e=>ZB(e,V(r3,e=>()=>R(function*(){let t=yield*lM,n=new Headers(t.headers),r=yield*V4(()=>e.auth.api.getSession({headers:n}),{unavailable:B4});return r?{providerHeaders:F(n),userId:r.user.id,email:r.user.email,writable:!0}:yield*new CI({message:`Owner session required`})}))),fwe=iH(W({id:U,email:U})),pwe=e=>ZB(dV,R(function*(){let{sql:t}=yield*cH,n=yield*k9,r=()=>new CI({message:`Owner authorization required`});return i=>R(function*(){let a=yield*U9(e.verifier,i).pipe(mp(`ProviderUnavailable`,()=>z(new $B({message:`Request could not be completed`}))));if(a.actor.kind!==`client`)return yield*r();let o=a.scopes.includes(pV.write);if(!o&&!a.scopes.includes(pV.read))return yield*new TI({message:`Insufficient scope`,scopes:[pV.read]});let s=yield*t`SELECT u.id, u.email FROM user u
|
|
538
|
+
JOIN oauthClient c ON c.clientId = ${a.actor.clientId}
|
|
539
|
+
WHERE u.id = ${a.subject} AND c.disabled IS NOT 1`;if(!s[0])return yield*r();let c=yield*fwe(s[0]);return n.caller(c.id,c.email,o)})}),{protectedResource:e.protectedResource}),mwe=e=>e.readOnly?L:B(cV,({writable:e})=>e?L:z(new TI({message:`This action requires the ${pV.write} scope`,scopes:[pV.write]}))),hwe=OM()(e=>R(function*(){let t=[],n=yield*Lp(e,A9,{add:e=>I(()=>t.push(...e))});return t.length?_j(n,Lh(t)):n}));function gwe(e){return vf(R(function*(){let{context:t}=yield*r3,n=yield*u3,r=yield*l3,i=yield*twe,a=yield*a3,o=sL(qV,{listClients:n.list,createClient:n.create,updateClient:n.update,deleteClient:n.delete,revokeClient:n.revoke,blockClient:n.block,rotateClientSecret:n.rotate,setClientAccess:r.setAccess,getResource:r.get,putResource:r.put,deleteResource:r.delete,listApiKeys:a.list,createApiKey:a.create,updateApiKey:a.update,deleteApiKey:a.delete},{authorize:mwe}),s=sL(GV,{setupStatus:i.setupStatus,setupOwner:i.setupOwner,keyList:({resource:e})=>a.keyList(e)}),c=yield*lwe(),l=lV(t.authCookies.sessionToken.name),u=YV(l),d=bf(yB(u,o).pipe(Cf(dwe(l))),SM(`GET`,`/openapi.json`,uj(XR(u.api))),yB(u,s).pipe(Cf(hwe.layer))),f=bf(JCe(o,{name:`clankerauth-admin`,version:YCe,allowedOrigins:e,instructions:`Owner administration. Listing needs ${pV.read} or ${pV.write}; every other action changes authorization policy and needs ${pV.write}. Create and rotate actions return secrets once.`,authentication:dV}),yB(XV,o)).pipe(Cf(pwe(c)));return bf(d,f)}))}const W9=`clankerauth_forward`,G9=(e,t)=>uj({error:t},{status:e}),_we=e=>vf(R(function*(){let t=yield*Y4,{auth:n,context:r}=yield*r3,i=yield*n3,a=n=>{if(!URL.canParse(n))return;let r=new URL(n);return!r.username&&!r.password&&G4(r,t.allowInsecureHttp)&&W4(r.hostname,e)?r:void 0},o=cg(t.secret),s=new URL(`/login`,t.baseURL),c={domain:e,path:`/`,httpOnly:!0,secure:t.baseURL.startsWith(`https:`),sameSite:`lax`},l=r.authCookies.sessionToken.name,u=(e,n)=>{let r=new URL(e,t.baseURL);return r.searchParams.set(`rd`,n.href),r},d=e=>V4(()=>n.api.getSession({headers:new Headers({cookie:e})}),{unavailable:B4}),f=R(function*(){let e=yield*lM,{headers:r}=e,s=r[`x-forwarded-proto`],c=r[`x-forwarded-host`],f=s&&c?a(`${s}://${c}${r[`x-forwarded-uri`]??`/`}`):void 0;if(!f)return G9(400,`invalid_forwarded_request`);let p=new URL(e.url,t.baseURL).searchParams.get(`resource`),m=p&&(yield*i.application(p));if(!m)return G9(403,`unknown_resource`);let h=e.cookies[W9],g=h?yield*nie(ZCe(o,h)):Ai(),_=Ni(g)?yield*d(`${l}=${g.value}`):null;if(!_)return r[`sec-fetch-mode`]===`navigate`?oj(u(`/forward-auth/continue`,f)):G9(401,`unauthenticated`);let v=Math.floor((yield*Ef)/1e3),{token:y}=yield*V4(()=>n.api.signDocument({body:{typ:`at+jwt`,payload:{sub:_.user.id,aud:m.identifier,client_id:`forward-auth`,scope:m.scopes.join(` `),iat:v,exp:v+900}}}));return aj({status:204,headers:{authorization:`Bearer ${y}`}})}),p=R(function*(){let e=yield*lM,n=new URL(e.url,t.baseURL).searchParams.get(`rd`),r=n?a(n):void 0;if(!r)return G9(400,`invalid_return_url`);let i=e.cookies[l];if(!(i&&(yield*d(e.headers.cookie??``)))||!i)return oj(u(`/login`,u(`/forward-auth/continue`,r)));let s=yield*XCe(o,i);return yield*oj(r).pipe(gj(W9,s,c))}),m=R(function*(){let e=yield*lM,r=new URL(e.url,t.baseURL).searchParams.get(`rd`),i=r&&a(r)||s,{headers:o}=yield*V4(()=>n.api.signOut({headers:new Headers({cookie:e.headers.cookie??``}),returnHeaders:!0}),{refused:z4,unavailable:B4});return yield*_j(oj(i),Lh(o.getSetCookie())).pipe(gj(W9,``,{...c,maxAge:0}))});return bf(SM(`GET`,`/forward-auth`,pp(f,U4)),SM(`GET`,`/forward-auth/continue`,pp(p,U4)),SM(`GET`,`/forward-auth/logout`,pp(m,U4)))})),vwe=/* @__PURE__ */ new Set([`/sign-in/email`,`/sign-out`,`/get-session`,`/change-password`,`/jwks`,`/oauth2/register`,`/oauth2/authorize`,`/oauth2/token`,`/oauth2/consent`,`/oauth2/continue`,`/oauth2/public-client`,`/oauth2/introspect`,`/oauth2/revoke`,`/.well-known/oauth-authorization-server`]),ywe=/* @__PURE__ */ new Set([`/.well-known/oauth-protected-resource`,`/jwks`,`/oauth2/register`,`/oauth2/token`,`/oauth2/revoke`,`/oauth2/introspect`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),bwe=/* @__PURE__ */ new Set([`/jwks`,`/.well-known/oauth-protected-resource`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),xwe=new Set(Cbe),Swe=/^\/assets\/[a-zA-Z0-9_.-]+\.(js|css|woff2)$/,K9=(e,t=200)=>uj(e,{status:t}),q9=K9({error:`Not found`},404),J9=[`Authorization`,`Content-Type`,`Accept`,`Mcp-Protocol-Version`,`Mcp-Method`,`Mcp-Name`],Cwe=new Set(J9.map(e=>e.toLowerCase())),wwe=(e=gt(new URL(`dist/`,import.meta.resolve(`@clankerauth/web/package.json`))))=>vf(R(function*(){let t=yield*Y4,{auth:n}=yield*r3,{sql:r}=yield*cH,i=yield*n3,a=[.../* @__PURE__ */ new Set([t.baseURL,...t.mcpAllowedOrigins])],o=R(function*(){let e=yield*lM,r=new URL(e.url,t.baseURL),a=r.pathname.replace(/^\/api\/auth/,``);if(!vwe.has(a)&&a!==`/.well-known/oauth-authorization-server/api/auth`)return q9;if(a===`/oauth2/authorize`){let t=e.method===`GET`?r.searchParams.getAll(`resource`):new URLSearchParams(yield*e.text).getAll(`resource`);if(t.length!==1||!(yield*i.get(t[0]??``)))return K9({error:`invalid_target`,error_description:X4},400)}let o=e.method===`GET`||e.method===`HEAD`?void 0:yield*e.arrayBuffer,s=yield*V4(()=>n.handler(new Request(r,{method:e.method,headers:e.headers,body:o})));return cce(s)}).pipe(pp(U4)),s=xM(n=>R(function*(){let r=yield*wj;yield*n.add(`*`,`/*`,R(function*(){let n=yield*lM;if(n.method!==`GET`&&n.method!==`HEAD`)return q9;let i=new URL(n.url,t.baseURL).pathname,a=xwe.has(i)?`index.html`:Swe.test(i)?i.slice(1):void 0;return a?yield*r.fileResponse(mt(e,a),{contentType:a.endsWith(`.js`)?`text/javascript`:a.endsWith(`.css`)?`text/css`:a.endsWith(`.woff2`)?`font/woff2`:`text/html; charset=utf-8`}).pipe(pp(()=>F(q9))):q9}))})),c=OM(e=>$ye({baseURL:t.baseURL,trustProxy:t.trustProxy})(R(function*(){let n=yield*lM,r=new URL(n.url,t.baseURL).pathname,i=r.replace(/^\/api\/auth/,``),o=r===`/mcp`,s=n.headers.origin,c=s!==void 0&&a.includes(s),l=ywe.has(i),u;if(o&&s!==void 0&&!c)u=K9({error:`Invalid origin`},403);else if(o&&n.method===`OPTIONS`){let e=n.headers[`access-control-request-method`],t=(n.headers[`access-control-request-headers`]??``).split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);u=c&&e===`POST`&&t.every(e=>Cwe.has(e))?aj({status:204}):K9({error:`MCP preflight rejected`},403)}else u=l&&n.method===`OPTIONS`?aj({status:204}):yield*e;l&&(u=u.pipe(hj({"access-control-allow-origin":`*`,"access-control-allow-methods":`GET, POST, OPTIONS`,"access-control-allow-headers":`Authorization, Content-Type, DPoP`,"access-control-expose-headers":`WWW-Authenticate, DPoP-Nonce`}),mj(`access-control-allow-credentials`))),o&&(u=u.pipe(pj(`vary`,u.headers.vary?`${u.headers.vary}, Origin`:`Origin`),mj(`access-control-allow-credentials`)),c&&s!==void 0&&(u=u.pipe(hj({"access-control-allow-origin":s,"access-control-expose-headers":`WWW-Authenticate, Mcp-Protocol-Version`})),n.method===`OPTIONS`&&u.status>=200&&u.status<300&&(u=u.pipe(hj({"access-control-allow-methods":`POST`,"access-control-allow-headers":J9.join(`, `)})))));let d=n.method!==`GET`||u.status!==200?`no-store`:r.startsWith(`/assets/`)?`public, max-age=31536000, immutable`:bwe.has(i)?`public, max-age=300`:`no-store`;return u=u.pipe(hj({"cache-control":d,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`,"x-frame-options":`DENY`,"content-security-policy":`default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`})),t.baseURL.startsWith(`https:`)&&(u=u.pipe(pj(`strict-transport-security`,`max-age=31536000`))),u})),{global:!0}),l=OM(e=>Xp(e));return bf(gwe(a),t.cookieDomain===void 0?ff:_we(t.cookieDomain),SM(`GET`,`/healthz`,r`SELECT 1`.pipe(dp(K9({status:`ok`})),pp(U4))),SM(`*`,`/api/auth/*`,o),SM(`*`,`/.well-known/*`,o),s).pipe(Cf(l.layer),Cf(c),Cf(Hue))})),Twe=um(`Http.nodeHandler`)(function*(e){let t=yield*_le(wwe(e));return yield*Bue(t,{scope:yield*Rp})}),Ewe=(e,t)=>{let n=vf(V(Y4,({database:e})=>cH.layer(e)));return bf(k9.layer,u3.layer,a3.layer).pipe(wf(l3.layer),wf(r3.layer),wf(n3.layer),wf(n),wf(xf(e,t)))},Y9=`credentials.json`,X9=W({email:U,password:U,secret:U,clientId:Nx(U),clientSecret:Nx(U)}),Dwe=Cx(bS(X9)),Owe=kx(X9),Z9=(e,t)=>B($E,n=>n.writeFileString(pt(e,Y9),`${JSON.stringify(Owe(t),null,2)}\n`,{mode:384})),kwe=um(`Dev.identity`)(function*(e,t){let n={email:`owner@example.internal`,password:ct(24).toString(`base64url`),secret:ct(32).toString(`hex`)};if(!t)return n;let r=yield*$E,i=pt(e,Y9);return(yield*r.exists(i))?yield*Dwe(yield*r.readFileString(i)):(yield*Z9(e,n),n)}),Q9=e=>Error(`Disposable issuer provisioning failed`,{cause:e}),$9=um(`Dev.ownerSession`)(function*(e,t,n,r){if(t===void 0)return yield*z(/* @__PURE__ */ Error(`A forward-auth session needs a cookieDomain; the issuer serves none`));let i=yield*FA,a=yield*i.execute(bA(`${e}/api/auth/sign-in/email`,{headers:{origin:e}}).pipe(wA(n)));if(yield*a.text,a.status!==200)return yield*z(/* @__PURE__ */ Error(`Owner sign-in failed with HTTP ${a.status}`));let o=new URL(`/`,r).href,s=yield*i.get(`${e}/forward-auth/continue?rd=${encodeURIComponent(o)}`,{headers:{cookie:Zh(a.cookies)}});yield*s.text;let c=Jh(a.cookies,s.cookies);return{cookie:Zh(c),cookies:Object.entries(Qh(c)).map(([e,t])=>({name:e,value:t}))}}),Awe=bf(DN,jN,uf(AN,{redirect:`manual`})),jwe=H(function*(e){let t=yield*$E,n=gt(new URL(`./web/`,import.meta.url));if(!(yield*t.exists(pt(n,`index.html`))))return yield*z(/* @__PURE__ */ Error(`The @gjermundgaraba/clankerauth-dev installation is missing its bundled dashboard assets`));let r=e.dataDir,i=r===void 0?yield*t.makeTempDirectoryScoped({prefix:`clankerauth-disposable-`}):yield*dp(t.makeDirectory(mt(r),{recursive:!0,mode:448}),mt(r)),a=yield*Yye(e.port??0,`127.0.0.1`),{port:o}=a,s=e.cookieDomain===void 0?`http://127.0.0.1:${o}`:`http://clankerauth.${e.cookieDomain}:${o}`,c=yield*kwe(i,r!==void 0),l=yield*J4({baseURL:s,secret:og(c.secret),database:pt(i,`issuer.sqlite`),host:`127.0.0.1`,port:o,mcpAllowedOrigins:[],trustProxy:!1,allowInsecureHttp:e.cookieDomain!==void 0,cookieDomain:e.cookieDomain}),u=yield*kre(Ewe(uf(Y4,l),N4.layerWith(e.cimdTransport))),d=da(u,k9),f=yield*Zd(yield*Rp),p=yield*Twe(n).pipe(Mp(u),Lp(Kd,f));yield*a.serve((t,n)=>{try{e.onRequest?.({method:t.method??`GET`,url:new URL(t.url??`/`,`http://127.0.0.1:${t.socket.localPort}`)}),p(t,n)}catch{n.headersSent?n.destroy():n.writeHead(500).end(`Request failed`)}});let m={email:c.email,password:c.password},h=da(u,u3),g=da(u,l3),_=da(u,a3),v=e=>Xp(zp(R(function*(){let t=yield*d.find();return t===void 0?yield*rp(/* @__PURE__ */ Error(`Owner setup failed`)):yield*e(t).pipe(Lp(cV,d.caller(t,m.email,!0)))}))).pipe(vp(Q9));(yield*d.find())||(yield*d.create(m).pipe(vp(Q9))),yield*v(()=>qf(e.resources,e=>g.put(e),{discard:!0}));let y=yield*v(()=>R(function*(){if(c.clientId!==void 0&&c.clientSecret!==void 0){let{clients:e}=yield*h.list();if(e.some(e=>e.client_id===c.clientId))return{client_id:c.clientId,client_secret:c.clientSecret}}return yield*h.create({client_name:e.client.name,redirect_uris:[e.client.redirect],resources:e.client.resources,token_endpoint_auth_method:`client_secret_basic`,application_type:`native`})})),b=y.client_secret;if(b===void 0)return yield*z(/* @__PURE__ */ Error(`Disposable issuer did not return client credentials`));r!==void 0&&(yield*Z9(i,{...c,clientId:y.client_id,clientSecret:b}));let x=e.cookieDomain===void 0?void 0:s;return{details:{issuer:`${s}/api/auth`,clientId:y.client_id,clientSecret:b,owner:m,url:s,port:o,directory:i},apiKey:e=>v(()=>V(_.create({name:e.name??`development`,permissions:e.permissions,expiresAt:null}),e=>e.key)),ownerSession:e=>$9(s,x,m,e),ownerToken:um(`Dev.ownerToken`)(function*(e){let{cookie:t}=yield*$9(s,x,m,e.appOrigin),n=yield*FA,r=new URL(e.appOrigin),i=new URL(`/forward-auth`,s);i.searchParams.set(`resource`,e.resource);let a=yield*n.get(i,{headers:{cookie:t,"x-forwarded-proto":r.protocol.slice(0,-1),"x-forwarded-host":r.host,"x-forwarded-uri":`/`}});yield*a.text;let o=a.headers.authorization;return a.status!==204||o===void 0?yield*z(/* @__PURE__ */ Error(`Forward auth issued no token (HTTP ${a.status})`)):o.replace(/^Bearer /iu,``)})}});async function Mwe(e){let t=qd(),n=e=>sm(e.pipe(Lp(Kd,t),Mp(Awe)),{onFiberStart:$S(t)}),r=cm(Kp($d(t,Md)));try{let t=await n(jwe(e));return{...t.details,apiKey:e=>n(t.apiKey(e)),ownerSession:e=>n(t.ownerSession(e)),ownerToken:e=>n(t.ownerToken(e)),close:()=>sm(r)}}catch(e){throw await sm(r),e}}export{ZV as n,Mwe as t};
|