1import{z as f}from"./index-Sf82o0Rs.js";import{r as We}from"./chunk-AYJ5UCUI-C1HMqFsr.js";import{e as Dr}from"./env-WZO7pDRw.js";let x=[],Y=0;const ke=4;let Nt=e=>{let t=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=t.push(n),()=>{for(let i=Y+ke;i<x.length;)x[i]===n?x.splice(i,ke):i+=ke;let s=t.indexOf(n);~s&&(t.splice(s,1),--r.lc||r.off())}},notify(n,s){let i=!x.length;for(let a of t)x.push(a,r.value,n,s);if(i){for(Y=0;Y<x.length;Y+=ke)x[Y](x[Y+1],x[Y+2],x[Y+3]);x.length=0}},off(){},set(n){let s=r.value;s!==n&&(r.value=n,r.notify(s))},subscribe(n){let s=r.listen(n);return n(r.value),s},value:e};return r};const Lr=5,Ie=6,ve=10;let Nr=(e,t,r,n)=>(e.events=e.events||{},e.events[r+ve]||(e.events[r+ve]=n(s=>{e.events[r].reduceRight((i,a)=>(a(i),i),{shared:{},...s})})),e.events[r]=e.events[r]||[],e.events[r].push(t),()=>{let s=e.events[r],i=s.indexOf(t);s.splice(i,1),s.length||(delete e.events[r],e.events[r+ve](),delete e.events[r+ve])}),Pr=1e3,Cr=(e,t)=>Nr(e,n=>{let s=t(n);s&&e.events[Ie].push(s)},Lr,n=>{let s=e.listen;e.listen=(...a)=>(!e.lc&&!e.active&&(e.active=!0,n()),s(...a));let i=e.off;return e.events[Ie]=[],e.off=()=>{i(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let a of e.events[Ie])a();e.events[Ie]=[]}},Pr)},()=>{e.listen=s,e.off=i}});function $r(e,t,r){let n=new Set(t).add(void 0);return e.listen((s,i,a)=>{n.has(a)&&r(s,i,a)})}var Vr=Object.defineProperty,xr=Object.defineProperties,jr=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertySymbols,Wr=Object.prototype.hasOwnProperty,qr=Object.prototype.propertyIsEnumerable,ft=(e,t,r)=>t in e?Vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,W=(e,t)=>{for(var r in t||(t={}))Wr.call(t,r)&&ft(e,r,t[r]);if(ut)for(var r of ut(t))qr.call(t,r)&&ft(e,r,t[r]);return e},J=(e,t)=>xr(e,jr(t)),Hr=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},Mr=async(e,t)=>{var r,n,s,i,a,o;let d=t||{};const c={onRequest:[t==null?void 0:t.onRequest],onResponse:[t==null?void 0:t.onResponse],onSuccess:[t==null?void 0:t.onSuccess],onError:[t==null?void 0:t.onError],onRetry:[t==null?void 0:t.onRetry]};if(!t||!(t!=null&&t.plugins))return{url:e,options:d,hooks:c};for(const l of(t==null?void 0:t.plugins)||[]){if(l.init){const u=await((r=l.init)==null?void 0:r.call(l,e.toString(),t));d=u.options||d,e=u.url}c.onRequest.push((n=l.hooks)==null?void 0:n.onRequest),c.onResponse.push((s=l.hooks)==null?void 0:s.onResponse),c.onSuccess.push((i=l.hooks)==null?void 0:i.onSuccess),c.onError.push((a=l.hooks)==null?void 0:a.onError),c.onRetry.push((o=l.hooks)==null?void 0:o.onRetry)}return{url:e,options:d,hooks:c}},ht=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}},Br=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 Jr(e){if(typeof e=="number")return new ht({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new ht(e);case"exponential":return new Br(e);default:throw new Error("Invalid retry strategy")}}var Kr=async e=>{const t={},r=async n=>typeof n=="function"?await n():n;if(e!=null&&e.auth){if(e.auth.type==="Bearer"){const n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if(e.auth.type==="Basic"){const n=r(e.auth.username),s=r(e.auth.password);if(!n||!s)return t;t.authorization=`Basic ${btoa(`${n}:${s}`)}`}else if(e.auth.type==="Custom"){const n=r(e.auth.value);if(!n)return t;t.authorization=`${r(e.auth.prefix)} ${n}`}}return t},zr=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Fr(e){const t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";const n=t.split(";").shift()||"";return zr.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Zr(e){try{return JSON.parse(e),!0}catch{return!1}}function Pt(e){if(e===void 0)return!1;const t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function pt(e){try{return JSON.parse(e)}catch{return e}}function mt(e){return typeof e=="function"}function Gr(e){if(e!=null&&e.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&mt(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&mt(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Qr(e){const t=new Headers(e==null?void 0:e.headers),r=await Kr(e);for(const[n,s]of Object.entries(r||{}))t.set(n,s);if(!t.has("content-type")){const n=Yr(e==null?void 0:e.body);n&&t.set("content-type",n)}return t}function Yr(e){return Pt(e)?"application/json":null}function Xr(e){if(!(e!=null&&e.body))return null;const t=new Headers(e==null?void 0:e.headers);if(Pt(e.body)&&!t.has("content-type")){for(const[r,n]of Object.entries(e==null?void 0:e.body))n instanceof Date&&(e.body[r]=n.toISOString());return JSON.stringify(e.body)}return e.body}function en(e,t){var r;if(t!=null&&t.method)return t.method.toUpperCase();if(e.startsWith("@")){const n=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return $t.includes(n)?n.toUpperCase():t!=null&&t.body?"POST":"GET"}return t!=null&&t.body?"POST":"GET"}function tn(e,t){let r;return!(e!=null&&e.signal)&&(e!=null&&e.timeout)&&(r=setTimeout(()=>t==null?void 0:t.abort(),e==null?void 0:e.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}
1var rn=class Ct extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,Ct.prototype)}};async function Le(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new rn(r.issues);return r.value}var $t=["get","post","put","patch","delete"],nn=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,r){var n,s,i,a;const o=((s=(n=e.plugins)==null?void 0:n.find(d=>{var c;return(c=d.schema)!=null&&c.config?t.startsWith(d.schema.config.baseURL||"")||t.startsWith(d.schema.config.prefix||""):!1}))==null?void 0:s.schema)||e.schema;if(o){let d=t;(i=o.config)!=null&&i.prefix&&d.startsWith(o.config.prefix)&&(d=d.replace(o.config.prefix,""),o.config.baseURL&&(t=t.replace(o.config.prefix,o.config.baseURL))),(a=o.config)!=null&&a.baseURL&&d.startsWith(o.config.baseURL)&&(d=d.replace(o.config.baseURL,""));const c=o.schema[d];if(c){let l=J(W({},r),{method:c.method,output:c.output});return r!=null&&r.disableValidation||(l=J(W({},l),{body:c.input?await Le(c.input,r==null?void 0:r.body):r==null?void 0:r.body,params:c.params?await Le(c.params,r==null?void 0:r.params):r==null?void 0:r.params,query:c.query?await Le(c.query,r==null?void 0:r.query):r==null?void 0:r.query})),{url:t,options:l}}}return{url:t,options:r}}}),sn=e=>{async function t(r,n){const s=J(W(W({},e),n),{plugins:[...(e==null?void 0:e.plugins)||[],nn(e||{})]});if(e!=null&&e.catchAllError)try{return await R(r,s)}catch(i){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:i}}}return await R(r,s)}return t};function an(e,t){let{baseURL:r,params:n,query:s}=t||{query:{},params:{},baseURL:""},i=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){const u=e.toString().split("@")[1].split("/")[0];$t.includes(u)&&(e=e.replace(`@${u}/`,"/"))}i.endsWith("/")||(i+="/");let[a,o]=e.replace(i,"").split("?");const d=new URLSearchParams(o);for(const[u,h]of Object.entries(s||{}))h!=null&&d.set(u,String(h));if(n)if(Array.isArray(n)){const u=a.split("/").filter(h=>h.startsWith(":"));for(const[h,p]of u.entries()){const w=n[h];a=a.replace(p,w)}}else for(const[u,h]of Object.entries(n))a=a.replace(`:${u}`,String(h));a=a.split("/").map(encodeURIComponent).join("/"),a.startsWith("/")&&(a=a.slice(1));let c=d.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",i.startsWith("http")?new URL(`${a}${c}`,i):`${i}${a}${c}`}var R=async(e,t)=>{var r,n,s,i,a,o,d,c;const{hooks:l,url:u,options:h}=await Mr(e,t),p=Gr(h),w=new AbortController,A=(r=h.signal)!=null?r:w.signal,y=an(u,h),_=Xr(h),g=await Qr(h),T=en(u,h);let E=J(W({},h),{url:y,headers:g,body:_,method:T,signal:A});for(const I of l.onRequest)if(I){const D=await I(E);D instanceof Object&&(E=D)}("pipeTo"in E&&typeof E.pipeTo=="function"||typeof((n=t==null?void 0:t.body)==null?void 0:n.pipe)=="function")&&("duplex"in E||(E.duplex="half"));const{clearTimeout:k}=tn(h,w);let S=await p(E.url,E);k();const G={response:S,request:E};for(const I of l.onResponse)if(I){const D=await I(J(W({},G),{response:(s=t==null?void 0:t.hookOptions)!=null&&s.cloneResponse?S.clone():S}));D instanceof Response?S=D:D instanceof Object&&(S=D.response)}if(S.ok){if(!(E.method!=="HEAD"))return{data:"",error:null};const D=Fr(S),M={data:"",response:S,request:E};if(D==="json"||D==="text"){const V=await S.text(),Or=await((i=E.jsonParser)!=null?i:pt)(V);M.data=Or}else M.data=await S[D]();E!=null&&E.output&&E.output&&!E.disableValidation&&(M.data=await Le(E.output,M.data));for(const V of l.onSuccess)V&&await V(J(W({},M),{response:(a=t==null?void 0:t.hookOptions)!=null&&a.cloneResponse?S.clone():S}));return t!=null&&t.throw?M.data:{data:M.data,error:null}}const Ue=(o=t==null?void 0:t.jsonParser)!=null?o:pt,ne=await S.text(),we=Zr(ne),de=we?await Ue(ne):null,O={response:S,responseText:ne,request:E,error:J(W({},de),{status:S.status,statusText:S.statusText})};for(const I of l.onError)I&&await I(J(W({},O),{response:(d=t==null?void 0:t.hookOptions)!=null&&d.cloneResponse?S.clone():S}));if(t!=null&&t.retry){const I=Jr(t.retry),D=(c=t.retryAttempt)!=null?c:0;if(await I.shouldAttemptRetry(D,S)){for(const V of l.onRetry)V&&await V(G);const M=I.getDelay(D);return await new Promise(V=>setTimeout(V,M)),await R(e,J(W({},t),{retryAttempt:D+1}))}}if(t!=null&&t.throw)throw new Hr(S.status,S.statusText,we?de:ne);return{data:null,error:J(W({},de),{status:S.status,statusText:S.statusText})}},on={},cn={};const Ne=Object.create(null),ye=e=>{var t;return on||((t=globalThis.Deno)==null?void 0:t.env.toObject())||globalThis.__env__||(e?Ne:globalThis)},X=new Proxy(Ne,{get(e,t){return ye()[t]??Ne[t]},has(e,t){const r=ye();return t in r||t in Ne},set(e,t,r){const n=ye(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;const r=ye(!0);return delete r[t],!0},ownKeys(){const e=ye(!0);return Object.keys(e)}});function dn(e){return e?e!=="false":!1}const ze=typeof process<"u"&&cn&&"production"||"",ln=ze==="dev"||ze==="development";ze==="test"||dn(X.TEST);const un=(e,t,r,n)=>{const s=Nt({data:null,error:null,isPending:!0,isRefetching:!1,refetch:()=>i()}),i=()=>{const o=typeof n=="function"?n({data:s.get().data,error:s.get().error,
1isPending:s.get().isPending}):n;return r(t,{...o,async onSuccess(d){var c;typeof window<"u"&&s.set({data:d.data,error:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await((c=o==null?void 0:o.onSuccess)==null?void 0:c.call(o,d))},async onError(d){var h,p;const{request:c}=d,l=typeof c.retry=="number"?c.retry:(h=c.retry)==null?void 0:h.attempts,u=c.retryAttempt||0;l&&u<l||(s.set({error:d.error,data:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await((p=o==null?void 0:o.onError)==null?void 0:p.call(o,d)))},async onRequest(d){var l;const c=s.get();s.set({isPending:c.data===null,data:c.data,error:null,isRefetching:!0,refetch:s.value.refetch}),await((l=o==null?void 0:o.onRequest)==null?void 0:l.call(o,d))}})};e=Array.isArray(e)?e:[e];let a=!1;for(const o of e)o.subscribe(()=>{a?i():Cr(s,()=>(i(),a=!0,()=>{s.off(),o.off()}))});return s};class Ae extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}}function fn(e){return{authorize(t,r="AND"){let n=!1;for(const[s,i]of Object.entries(t)){const a=e[s];if(!a)return{success:!1,error:`You are not allowed to access resource: ${s}`};if(Array.isArray(i))n=i.every(o=>a.includes(o));else if(typeof i=="object"){const o=i;o.connector==="OR"?n=o.actions.some(d=>a.includes(d)):n=o.actions.every(d=>a.includes(d))}else throw new Ae("Invalid access control request");if(n&&r==="OR")return{success:n};if(!n&&r==="AND")return{success:!1,error:`unauthorized to access resource "${s}"`}}return n?{success:n}:{success:!1,error:"Not authorized"}},statements:e}}function hn(e){return{newRole(t){return fn(t)},statements:e}}const pn={user:["create","list","set-role","ban","impersonate","delete","set-password"],session:["list","revoke","delete"]},Vt=hn(pn),xt=Vt.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password"],session:["list","revoke","delete"]}),jt=Vt.newRole({user:[],session:[]}),mn={admin:xt,user:jt},gn=e=>{var n,s,i,a;if(e.userId&&((s=(n=e.options)==null?void 0:n.adminUserIds)!=null&&s.includes(e.userId)))return!0;if(!e.permissions&&!e.permission)return!1;const t=(e.role||((i=e.options)==null?void 0:i.defaultRole)||"user").split(","),r=((a=e.options)==null?void 0:a.roles)||mn;for(const o of t){const d=r[o],c=d==null?void 0:d.authorize(e.permission??e.permissions);if(c!=null&&c.success)return!0}return!1},wn=e=>{const t={admin:xt,user:jt,...e==null?void 0:e.roles};return{id:"admin-client",$InferServerPlugin:{},getActions:r=>({admin:{checkRolePermission:n=>gn({role:n.role,options:{ac:e==null?void 0:e.ac,roles:t},permissions:n.permissions??n.permission})}}),pathMethods:{"/admin/list-users":"GET","/admin/stop-impersonating":"POST"}}},_e=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));function Pe(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function Wt(e,t,r){let n="",s=0,i=0;for(const a of e)for(s=s<<8|a,i+=8;i>=6;)i-=6,n+=t[s>>i&63];if(i>0&&(n+=t[s<<6-i&63]),r){const a=(4-n.length%4)%4;n+="=".repeat(a)}return n}function qt(e,t){const r=new Map;for(let a=0;a<t.length;a++)r.set(t[a],a);const n=[];let s=0,i=0;for(const a of e){if(a==="=")break;const o=r.get(a);if(o===void 0)throw new Error(`Invalid Base64 character: ${a}`);s=s<<6|o,i+=6,i>=8&&(i-=8,n.push(s>>i&255))}return Uint8Array.from(n)}const xe={encode(e,t={}){const r=Pe(!1),n=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e);return Wt(n,r,t.padding??!0)},decode(e){typeof e!="string"&&(e=new TextDecoder().decode(e));const t=e.includes("-")||e.includes("_"),r=Pe(t);return qt(e,r)}},Te={encode(e,t={}){const r=Pe(!0),n=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e);return Wt(n,r,t.padding??!0)},decode(e){const t=e.includes("-")||e.includes("_"),r=Pe(t);return qt(e,r)}},Ht=globalThis.crypto,ae=Ht.subtle,yn=e=>Ht.getRandomValues(e),En="0123456789abcdef",gt={encode:e=>{if(typeof e=="string"&&(e=new TextEncoder().encode(e)),e.byteLength===0)return"";const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},decode:e=>{if(!e)return"";if(typeof e=="string"){if(e.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${En}]+$`).test(e))throw new Error("Invalid hexadecimal string");const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return new TextDecoder().decode(t)}return new TextDecoder().decode(e)}},Mt=(e="SHA-256",t="none")=>{const r={importKey:async(n,s)=>ae.importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:e}},!1,[s]),sign:async(n,s)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));const i=await ae.sign("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s);return t==="hex"?gt.encode(i):t==="base64"||t==="base64url"||t==="base64urlnopad"?Te.encode(i,{padding:t!=="base64urlnopad"}):i},verify:async(n,s,i)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),t==="hex"&&(i=gt.decode(i)),(t==="base64"||t==="base64url"||t==="base64urlnopad")&&(i=await xe.decode(i)),ae.verify("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i,typeof s=="string"?new TextEncoder().encode(s):s))};return r};function Bt(e){function t(r,n){if(typeof n=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(n)){const i=new Date(n);if(!isNaN(i.getTime()))return i}return n}try{return JSON.parse(e,t)}catch{return null}}function bn(e){try{return new URL(e).pathname!=="/"}catch{throw new Ae(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function qe(e,t="/api/auth"){return bn(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e.replace(/\/+$/,"")}${t}`)}function An(e,t,r){if(e)return qe(e,t);const n=X.BETTER_AUTH_URL||X.NEXT_PUBLIC_BETTER_AUTH_URL||X.PUBLIC_BETTER_AUTH_URL||X.NUXT_PUBLIC_BETTER_AUTH_URL||X.NUXT_PUBLIC_AUTH_URL||(X.BASE_URL!=="/"?X.BASE_URL:void 0);if(n)return qe(n,t);if(typeof window<"u"&&window.location)return qe(window.location.origin,t)}function _n(e){try{return new URL(e).origin}catch{return null}}function Sn(e){try{return new URL(e).protocol}catch{return null}}function Jt(e){try{return new URL(e).host}catch{return e}}async function Kt(e,t){var n,s;if((s=(n=e.context.options.session)==null?void 0:n.cookieCache)==null?void 0:s.enabled){const a={session:Object.entries(t.session).reduce((d,[c,l])=>{var h,p;const u=(p=(h=e.context.options.session)==null?void 0:h.additionalFields)==null?void 0:p[c];return(!u||u.returned!==!1)&&(d[c]=l),d},{}),user:t.user},o=Te.encode(JSON.stringify({session:a,expiresAt:_e(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Mt("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...a,expiresAt:_e(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime()}))}),{padding:!1});if(o.length>4093)throw new Ae("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,o,e.context.authCookies.sessionData.options)}}async function Z(e,t,r,n){var o;const s=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=r!==void 0?r:!!s;const i=e.context.authCookies.sessionToken.options,a=r?void 0:e.context.sessionConfig.expires
1In;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:a,...n}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await Kt(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await((o=e.context.secondaryStorage)==null?void 0:o.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3)))}function pe(e,t){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var Tn={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},m=class extends Error{constructor(e="INTERNAL_SERVER_ERROR",t=void 0,r={},n=typeof e=="number"?e:Tn[e]){var s;super(t==null?void 0:t.message),this.status=e,this.body=t,this.headers=r,this.statusCode=n,this.name="APIError",this.status=e,this.headers=r,this.statusCode=n,this.body=t?{code:(s=t==null?void 0:t.message)==null?void 0:s.toUpperCase().replace(/ /g,"_").replace(/[^A-Z0-9_]/g,""),...t}:void 0,this.stack=""}};function zt(e){return e instanceof m||(e==null?void 0:e.name)==="APIError"}function Rn(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}function Un(e){if(e===void 0)return!1;const t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function Fe(e,t){if(e instanceof Response)return(t==null?void 0:t.headers)instanceof Headers&&t.headers.forEach((s,i)=>{e.headers.set(i,s)}),e;if((e==null?void 0:e._flag)==="json"){const s=e.routerResponse;return s instanceof Response?s:Fe(e.body,{headers:e.headers,status:e.status})}if(zt(e))return Fe(e.body,{status:e.statusCode,statusText:e.status.toString(),headers:(t==null?void 0:t.headers)||e.headers});let r=e,n=new Headers(t==null?void 0:t.headers);return e?typeof e=="string"?(r=e,n.set("Content-Type","text/plain")):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(r=e,n.set("Content-Type","application/octet-stream")):e instanceof Blob?(r=e,n.set("Content-Type",e.type||"application/octet-stream")):e instanceof FormData?r=e:e instanceof URLSearchParams?(r=e,n.set("Content-Type","application/x-www-form-urlencoded")):e instanceof ReadableStream?(r=e,n.set("Content-Type","application/octet-stream")):Un(e)&&(r=JSON.stringify(e),n.set("Content-Type","application/json")):(e===null&&(r=JSON.stringify(null)),n.set("content-type","application/json")),new Response(r,{...t,headers:n})}async function kn(e,t={}){let r={body:t.body,query:t.query};if(e.body){const n=await e.body["~standard"].validate(t.body);if(n.issues)return{data:null,error:wt(n.issues,"body")};r.body=n.value}if(e.query){const n=await e.query["~standard"].validate(t.query);if(n.issues)return{data:null,error:wt(n.issues,"query")};r.query=n.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:"Headers is required"}}:e.requireRequest&&!t.request?{data:null,error:{message:"Request is required"}}:{data:r,error:null}}function wt(e,t){for(const r of e)r.message;return{message:`Invalid ${t} parameters`}}var nt={name:"HMAC",hash:"SHA-256"},Ft=async e=>{const t=typeof e=="string"?new TextEncoder().encode(e):e;return await ae.importKey("raw",t,nt,!1,["sign","verify"])},In=async(e,t,r)=>{try{const n=atob(e),s=new Uint8Array(n.length);for(let i=0,a=n.length;i<a;i++)s[i]=n.charCodeAt(i);return await ae.verify(nt,r,s,new TextEncoder().encode(t))}catch{return!1}},vn=async(e,t)=>{const r=await Ft(t),n=await ae.sign(nt.name,r,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(n)))},On=async(e,t)=>{const r=await vn(e,t);return e=`${e}.${r}`,e=encodeURIComponent(e),e},yt=(e,t)=>
1{let r=e;if(t)if(t==="secure")r="__Secure-"+e;else if(t==="host")r="__Host-"+e;else return;return r};function Dn(e){if(typeof e!="string")throw new TypeError("argument str must be a string");const t=new Map;let r=0;for(;r<e.length;){const n=e.indexOf("=",r);if(n===-1)break;let s=e.indexOf(";",r);if(s===-1)s=e.length;else if(s<n){r=e.lastIndexOf(";",n-1)+1;continue}const i=e.slice(r,n).trim();if(!t.has(i)){let a=e.slice(n+1,s).trim();a.codePointAt(0)===34&&(a=a.slice(1,-1)),t.set(i,Rn(a))}r=s+1}return t}var Zt=(e,t,r={})=>{let n;if((r==null?void 0:r.prefix)==="secure"?n=`${`__Secure-${e}`}=${t}`:(r==null?void 0:r.prefix)==="host"?n=`${`__Host-${e}`}=${t}`:n=`${e}=${t}`,e.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),e.startsWith("__Host-")&&(r.secure||(r.secure=!0),r.path!=="/"&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&typeof r.maxAge=="number"&&r.maxAge>=0){if(r.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&r.prefix!=="host"&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},Ln=(e,t,r)=>(t=encodeURIComponent(t),Zt(e,t,r)),Nn=async(e,t,r,n)=>(t=await On(t,r),Zt(e,t,n)),Gt=async(e,{options:t,path:r})=>{const n=new Headers,{data:s,error:i}=await kn(t,e);if(i)throw new m(400,{message:i.message,code:"VALIDATION_ERROR"});const a="headers"in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&e.request instanceof Request?e.request.headers:null,o=a==null?void 0:a.get("cookie"),d=o?Dn(o):void 0,c={...e,body:s.body,query:s.query,path:e.path||r,context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e==null?void 0:e.headers,request:e==null?void 0:e.request,params:"params"in e?e.params:void 0,method:e.method,setHeader:(l,u)=>{n.set(l,u)},getHeader:l=>a?a.get(l):null,getCookie:(l,u)=>{const h=yt(l,u);return h&&(d==null?void 0:d.get(h))||null},getSignedCookie:async(l,u,h)=>{const p=yt(l,h);if(!p)return null;const w=d==null?void 0:d.get(p);if(!w)return null;const A=w.lastIndexOf(".");if(A<1)return null;const y=w.substring(0,A),_=w.substring(A+1);if(_.length!==44||!_.endsWith("="))return null;const g=await Ft(u);return await In(_,y,g)?y:!1},setCookie:(l,u,h)=>{const p=Ln(l,u,h);return n.append("set-cookie",p),p},setSignedCookie:async(l,u,h,p)=>{const w=await Nn(l,u,h,p);return n.append("set-cookie",w),w},redirect:l=>(n.set("location",l),new m("FOUND",void 0,n)),error:(l,u,h)=>new m(l,u,h),json:(l,u)=>e.asResponse?{body:(u==null?void 0:u.body)||l,routerResponse:u,_flag:"json"}:l,responseHeaders:n};for(const l of t.use||[]){const u=await l({...c,returnHeaders:!0,asResponse:!1});u.response&&Object.assign(c.context,u.response),u.headers&&u.headers.forEach((h,p)=>{c.responseHeaders.set(p,h)})}return c};function he(e,t){const r=async n=>{const s=n,i=typeof e=="function"?e:t,o=await Gt(s,{options:typeof e=="function"?{}:e,path:"/"});if(!i)throw new Error("handler must be defined");const d=await i(o),c=o.responseHeaders;return s.returnHeaders?{headers:c,response:d}:d};return r.options=typeof e=="function"?{}:e,r}he.create=e=>{function t(r,n){if(typeof r=="function")return he({use:e==null?void 0:e.use},r);if(!n)throw new Error("Middleware handler is required");return he({...r,method:"*",use:[...(e==null?void 0:e.use)||[],...r.use||[]]},n)}return t};var Ze=(e,t,r)=>{const n=async(...s)=>{const i=s[0]||{},a=await Gt(i,{options:t,path:e}),o=await r(a).catch(async c=>{if(zt(c)){const l=t.onAPIError;if(l&&await l(c),i.asResponse)return c}throw c}),d=a.responseHeaders;return i.asResponse?Fe(o,{headers:d}):i.returnHeaders?{headers:d,response:o}:o};return n.options=t,n.path=e,n};Ze.create=e=>(t,r,n)=>Ze(t,{...r,use:[...(r==null?void 0:r.use)||[],...(e==null?void 0:e.use)||[]]},n);var Se;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function r(s){throw new Error}e.assertNever=r,e.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},e.getValidEnumValues=s=>{const i=e.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(const a of s)if(i(a))return a}
1,e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Se||(Se={}));var Et;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Et||(Et={}));Se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);Se.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var bt=class Qt extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,d=0;for(;d<a.path.length;){const c=a.path[d];d===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(r(a))):o[c]=o[c]||{_errors:[]},o=o[c],d++}}};return s(this),n}static assert(t){if(!(t instanceof Qt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const s of this.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(t(s))):n.push(t(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bt.create=e=>new bt(e);var At;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(At||(At={}));var _t;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(_t||(_t={}));const je=crypto,Yt=e=>e instanceof CryptoKey,z=new TextEncoder,re=new TextDecoder;function Xt(...e){const t=e.reduce((s,{length:i})=>s+i,0),r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const Pn=e=>{let t=e;typeof t=="string"&&(t=z.encode(t));const r=32768,n=[];for(let s=0;s<t.length;s+=r)n.push(String.fromCharCode.apply(null,t.subarray(s,s+r)));return btoa(n.join(""))},He=e=>Pn(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Cn=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},te=e=>{let t=e;t instanceof Uint8Array&&(t=re.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Cn(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class L extends Error{constructor(t,r){var n;super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}}L.code="ERR_JOSE_GENERIC";class j extends L{constructor(t,r,n="unspecified",s="unspecified"){super(t,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=s,this.payload=r}}j.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Ce extends L{constructor(t,r,n="unspecified",s="unspecified"){super(t,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=s,this.payload=r}}Ce.code="ERR_JWT_EXPIRED";class er extends L{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}er.code="ERR_JOSE_ALG_NOT_ALLOWED";class F extends L{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}F.code="ERR_JOSE_NOT_SUPPORTED";class $n extends L{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}$n.code="ERR_JWE_DECRYPTION_FAILED";class Vn extends L{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Vn.code="ERR_JWE_INVALID";class v extends L{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}v.code="ERR_JWS_INVALID";class q extends L{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}q.code="ERR_JWT_INVALID";class xn extends L{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}xn.code="ERR_JWK_INVALID";class st extends L{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}st.code="ERR_JWKS_INVALID";class it extends L{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}it.code="ERR_JWKS_NO_MATCHING_KEY";class tr extends L{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}tr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class rr extends L{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}}rr.code="ERR_JWKS_TIMEOUT";class nr extends L{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}nr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function B(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Ee(e,t){return e.name===t}function Me(e){return parseInt(e.name.slice(4),10)}function jn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Wn(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}
1function qn(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Ee(e.algorithm,"HMAC"))throw B("HMAC");const n=parseInt(t.slice(2),10);if(Me(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ee(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(Me(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ee(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");const n=parseInt(t.slice(2),10);if(Me(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw B("Ed25519 or Ed448");break}case"Ed25519":{if(!Ee(e.algorithm,"Ed25519"))throw B("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ee(e.algorithm,"ECDSA"))throw B("ECDSA");const n=jn(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Wn(e,r)}function sr(e,t,...r){var n;if(r=r.filter(Boolean),r.length>2){const s=r.pop();e+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&(n=t.constructor)!=null&&n.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const St=(e,...t)=>sr("Key must be ",e,...t);function ir(e,t,...r){return sr(`Key for the ${e} algorithm must be `,t,...r)}const ar=e=>Yt(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",$e=["CryptoKey"],or=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const i of s){if(r.has(i))return!1;r.add(i)}}return!0};function Hn(e){return typeof e=="object"&&e!==null}function H(e){if(!Hn(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const cr=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function ge(e){return H(e)&&typeof e.kty=="string"}function Mn(e){return e.kty!=="oct"&&typeof e.d=="string"}function Bn(e){return e.kty!=="oct"&&typeof e.d>"u"}function Jn(e){return ge(e)&&e.kty==="oct"&&typeof e.k=="string"}function Kn(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new F('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new F('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new F('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new F('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const dr=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=Kn(e),n=[t,e.ext??!1,e.key_ops??r],s={...e};return delete s.alg,delete s.use,je.subtle.importKey("jwk",s,...n)},lr=e=>te(e);let le,ue;const ur=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",Ve=async(e,t,r,n,s=!1)=>{let i=e.get(t);if(i!=null&&i[n])return i[n];const a=await dr({...r,alg:n});return s&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a},zn=(e,t)=>{if(ur(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?lr(r.k):(ue||(ue=new WeakMap),Ve(ue,e,r,t))}return ge(e)?e.k?te(e.k):(ue||(ue=new WeakMap),Ve(ue,e,e,t,!0)):e},Fn=(e,t)=>{if(ur(e)){let r=e.export({format:"jwk"});return r.k?lr(r.k):(le||(le=new WeakMap),Ve(le,e,r,t))}return ge(e)?e.k?te(e.k):(le||(le=new WeakMap),Ve(le,e,e,t,!0)):e},Tt={normalizePublicKey:zn,normalizePrivateKey:Fn};async function at(e,t){if(!H(e))throw new TypeError("JWK must be an object");
1switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return te(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new F('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return dr({...e,alg:t});default:throw new F('Unsupported "kty" (Key Type) Parameter value')}}const fe=e=>e==null?void 0:e[Symbol.toStringTag],Ge=(e,t,r)=>{var n,s;if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&((s=(n=t.key_ops).includes)==null?void 0:s.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Zn=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&ge(t)){if(Jn(t)&&Ge(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ar(t))throw new TypeError(ir(e,t,...$e,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${fe(t)} instances for symmetric algorithms must be of type "secret"`)}},Gn=(e,t,r,n)=>{if(n&&ge(t))switch(r){case"sign":if(Mn(t)&&Ge(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Bn(t)&&Ge(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ar(t))throw new TypeError(ir(e,t,...$e,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${fe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${fe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${fe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${fe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${fe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fr(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Zn(t,r,n,e):Gn(t,r,n,e)}fr.bind(void 0,!1);const Qe=fr.bind(void 0,!0);function hr(e,t,r,n,s){if(s.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(const a of n.crit){if(!i.has(a))throw new F(`Extension Header Parameter "${a}" is not recognized`);if(s[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}const Qn=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};function pr(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new F(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function mr(e,t,r){if(r==="sign"&&(t=await Tt.normalizePrivateKey(t,e)),r==="verify"&&(t=await Tt.normalizePublicKey(t,e)),Yt(t))return qn(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(St(t,...$e));return je.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(St(t,...$e,"Uint8Array","JSON Web Key"))}const Yn=async(e,t,r,n)=>{const s=await mr(e,t,"verify");cr(e,s);const i=pr(e,s.algorithm);
1try{return await je.subtle.verify(i,s,r,n)}catch{return!1}};async function Xn(e,t,r){if(!H(e))throw new v("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new v('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new v("JWS Protected Header incorrect type");if(e.payload===void 0)throw new v("JWS Payload missing");if(typeof e.signature!="string")throw new v("JWS Signature missing or incorrect type");if(e.header!==void 0&&!H(e.header))throw new v("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const A=te(e.protected);n=JSON.parse(re.decode(A))}catch{throw new v("JWS Protected Header is invalid")}if(!or(n,e.header))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...e.header},i=hr(v,new Map([["b64",!0]]),r==null?void 0:r.crit,n,s);let a=!0;if(i.has("b64")&&(a=n.b64,typeof a!="boolean"))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=s;if(typeof o!="string"||!o)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');const d=r&&Qn("algorithms",r.algorithms);if(d&&!d.has(o))throw new er('"alg" (Algorithm) Header Parameter value not allowed');if(a){if(typeof e.payload!="string")throw new v("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new v("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"?(t=await t(n,e),c=!0,Qe(o,t,"verify"),ge(t)&&(t=await at(t,o))):Qe(o,t,"verify");const l=Xt(z.encode(e.protected??""),z.encode("."),typeof e.payload=="string"?z.encode(e.payload):e.payload);let u;try{u=te(e.signature)}catch{throw new v("Failed to base64url decode the signature")}if(!await Yn(o,t,u,l))throw new nr;let p;if(a)try{p=te(e.payload)}catch{throw new v("Failed to base64url decode the payload")}else typeof e.payload=="string"?p=z.encode(e.payload):p=e.payload;const w={payload:p};return e.protected!==void 0&&(w.protectedHeader=n),e.header!==void 0&&(w.unprotectedHeader=e.header),c?{...w,key:t}:w}async function es(e,t,r){if(e instanceof Uint8Array&&(e=re.decode(e)),typeof e!="string")throw new v("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:i,length:a}=e.split(".");if(a!==3)throw new v("Invalid Compact JWS");const o=await Xn({payload:s,protected:n,signature:i},t,r),d={payload:o.payload,protectedHeader:o.protectedHeader};return typeof t=="function"?{...d,key:o.key}:d}const ee=e=>Math.floor(e.getTime()/1e3),gr=60,wr=gr*60,ot=wr*24,ts=ot*7,rs=ot*365.25,ns=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,be=e=>{const t=ns.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]),n=t[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*gr);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*wr);break;case"day":case"days":case"d":s=Math.round(r*ot);break;case"week":case"weeks":case"w":s=Math.round(r*ts);break;default:s=Math.round(r*rs);break}return t[1]==="-"||t[4]==="ago"?-s:s},Rt=e=>e.toLowerCase().replace(/^application\//,""),ss=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,is=(e,t,r={})=>{let n;try{n=JSON.parse(re.decode(t))}catch{}if(!H(n))throw new q("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&(typeof e.typ!="string"||Rt(e.typ)!==Rt(s)))throw new j('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:o,audience:d,maxTokenAge:c}=r,l=[...i];c!==void 0&&l.push("iat"),d!==void 0&&l.push("aud"),o!==void 0&&l.push("sub"),a!==void 0&&l.push("iss");for(const w of new Set(l.reverse()))if(!(w in n))throw new j(`missing required "${w}" claim`,n,w,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new j('unex
1pected "iss" claim value',n,"iss","check_failed");if(o&&n.sub!==o)throw new j('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!ss(n.aud,typeof d=="string"?[d]:d))throw new j('unexpected "aud" claim value',n,"aud","check_failed");let u;switch(typeof r.clockTolerance){case"string":u=be(r.clockTolerance);break;case"number":u=r.clockTolerance;break;case"undefined":u=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=r,p=ee(h||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new j('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new j('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+u)throw new j('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new j('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-u)throw new Ce('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const w=p-n.iat,A=typeof c=="number"?c:be(c);if(w-u>A)throw new Ce('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(w<0-u)throw new j('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function ct(e,t,r){var a;const n=await es(e,t,r);if((a=n.protectedHeader.crit)!=null&&a.includes("b64")&&n.protectedHeader.b64===!1)throw new q("JWTs MUST NOT use unencoded payload");const i={payload:is(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}const as=async(e,t,r)=>{const n=await mr(e,t,"sign");cr(e,n);const s=await je.subtle.sign(pr(e,n.algorithm),n,r);return new Uint8Array(s)};class os{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new v("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!or(this._protectedHeader,this._unprotectedHeader))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader},s=hr(v,new Map([["b64",!0]]),r==null?void 0:r.crit,this._protectedHeader,n);let i=!0;if(s.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;
1if(typeof a!="string"||!a)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');Qe(a,t,"sign");let o=this._payload;i&&(o=z.encode(He(o)));let d;this._protectedHeader?d=z.encode(He(JSON.stringify(this._protectedHeader))):d=z.encode("");const c=Xt(d,z.encode("."),o),l=await as(a,t,c),u={signature:He(l),payload:""};return i&&(u.payload=re.decode(o)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=re.decode(d)),u}}class cs{constructor(t){this._flattened=new os(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){const n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function se(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ds{constructor(t={}){if(!H(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:se("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:se("setNotBefore",ee(t))}:this._payload={...this._payload,nbf:ee(new Date)+be(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:se("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:se("setExpirationTime",ee(t))}:this._payload={...this._payload,exp:ee(new Date)+be(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:ee(new Date)}:t instanceof Date?this._payload={...this._payload,iat:se("setIssuedAt",ee(t))}:typeof t=="string"?this._payload={...this._payload,iat:se("setIssuedAt",ee(new Date)+be(t))}:this._payload={...this._payload,iat:se("setIssuedAt",t)},this}}class ls extends ds{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var s;const n=new cs(z.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((s=this._protectedHeader)==null?void 0:s.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new q("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}}function us(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new F('Unsupported "alg" value for a JSON Web Key Set')}}function fs(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(hs)}function hs(e){return H(e)}function yr(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}class ps{constructor(t){if(this._cached=new WeakMap,!fs(t))throw new st("JSON Web Key Set malformed");this._jwks=yr(t)}async getKey(t,r){const{alg:n,kid:s}={...t,...r==null?void 0:r.header},i=us(n),a=this._jwks.keys.filter(c=>{let l=i===c.kty;if(l&&typeof s=="string"&&(l=s===c.kid),l&&typeof c.alg=="string"&&(l=n===c.alg),l&&typeof c.use=="string"&&(l=c.use==="sig"),l&&Array.isArray(c.key_ops)&&(l=c.key_ops.includes("verify")),l)switch(n){case"ES256":l=c.crv==="P-256";break;case"ES256K":l=c.crv==="secp256k1";break;case"ES384":l=c.crv==="P-384";break;case"ES512":l=c.crv==="P-521";break;case"Ed25519":l=c.crv==="Ed25519";break;case"EdDSA":l=c.crv==="Ed25519"||c.crv==="Ed448";break}return l}),{0:o,length:d}=a;if(d===0)throw new it;if(d!==1){const c=new tr,{_cached:l}=this;throw c[Symbol.asyncIterator]=async function*(){for(const u of a)try{yield await Ut(l,u,n)}catch{}},c}return Ut(this._cached,o,n)}}async function Ut(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const s=await at({...t,ext:!0},r);if(s instanceof Uint8Array||s.type!=="public")throw new st("JSON Web Key Set members must be public keys");n[r]=s}return n[r]}function kt(e){const t=new ps(e),r=async(n,s)=>t.getKey(n,s);return Object.defineProperties(r,{jwks:{value:()=>yr(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const ms=async(e,t,r)=>{let n,s,i=!1;typeof AbortController=="function"&&(n=new AbortController,s=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(o=>{throw i?new rr:o});if(s!==void 0&&clearTimeout(s),a.status!==200)throw new L("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new L("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function gs(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Ye;var De,Lt;(typeof navigator>"u"||!((Lt=(De=navigator.userAgent)==null?void 0:De.startsWith)!=null&&Lt.call(De,"Mozilla/5.0 ")))&&(Ye="jose/v5.10.0");const Be=Symbol();function ws(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>
1=t||!("jwks"in e)||!H(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,H))}class ys{constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Be])!==void 0&&(this._cache=r==null?void 0:r[Be],ws(r==null?void 0:r[Be],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=kt(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(t,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(t,r)}catch(n){if(n instanceof it&&this.coolingDown()===!1)return await this.reload(),this._local(t,r);throw n}}async reload(){this._pendingFetch&&gs()&&(this._pendingFetch=void 0);const t=new Headers(this._options.headers);Ye&&!t.has("User-Agent")&&(t.set("User-Agent",Ye),this._options.headers=Object.fromEntries(t.entries())),this._pendingFetch||(this._pendingFetch=ms(this._url,this._timeoutDuration,this._options).then(r=>{this._local=kt(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Es(e,t){const r=new ys(e,t),n=async(s,i)=>r.getKey(s,i);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var s;return(s=r._local)==null?void 0:s.jwks()},enumerable:!0,configurable:!1,writable:!1}}),n}const Er=te;function bs(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(re.decode(Er(t)));if(!H(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Re(e){if(typeof e!="string")throw new q("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new q("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new q("Invalid JWT");if(!t)throw new q("JWTs must contain a payload");let n;try{n=Er(t)}catch{throw new q("Failed to base64url decode the payload")}let s;try{s=JSON.parse(re.decode(n))}catch{throw new q("Failed to parse the decoded payload as JSON")}if(!H(s))throw new q("Invalid JWT Claims Set");return s}function As(e,t){return{digest:async r=>{const n=new TextEncoder,s=typeof r=="string"?n.encode(r):r;return await ae.digest(e,s)}}}async function br(e){const t=await As("SHA-256").digest(e);
1return Te.encode(new Uint8Array(t),{padding:!1})}function Ar(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?_e(e.expires_in,"sec"):void 0,scopes:e!=null&&e.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function $({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:s,scopes:i,claims:a,redirectURI:o,duration:d,prompt:c,accessType:l,responseType:u,display:h,loginHint:p,hd:w,responseMode:A,additionalParams:y,scopeJoiner:_}){const g=new URL(r);if(g.searchParams.set("response_type",u||"code"),g.searchParams.set("client_id",t.clientId),g.searchParams.set("state",n),g.searchParams.set("scope",i.join(_||" ")),g.searchParams.set("redirect_uri",t.redirectURI||o),d&&g.searchParams.set("duration",d),h&&g.searchParams.set("display",h),p&&g.searchParams.set("login_hint",p),c&&g.searchParams.set("prompt",c),w&&g.searchParams.set("hd",w),l&&g.searchParams.set("access_type",l),A&&g.searchParams.set("response_mode",A),s){const T=await br(s);g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("code_challenge",T)}if(a){const T=a.reduce((E,k)=>(E[k]=null,E),{});g.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...T}}))}return y&&Object.entries(y).forEach(([T,E])=>{g.searchParams.set(T,E)}),g}async function N({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:s,authentication:i,deviceId:a}){const o=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};
1if(o.set("grant_type","authorization_code"),o.set("code",e),t&&o.set("code_verifier",t),n.clientKey&&o.set("client_key",n.clientKey),a&&o.set("device_id",a),o.set("redirect_uri",n.redirectURI||r),i==="basic"){const h=Te.encode(`${n.clientId}:${n.clientSecret}`);d.authorization=`Basic ${h}`}else o.set("client_id",n.clientId),o.set("client_secret",n.clientSecret);const{data:c,error:l}=await R(s,{method:"POST",body:o,headers:d});if(l)throw l;return Ar(c)}async function P({refreshToken:e,options:t,tokenEndpoint:r,authentication:n,extraParams:s,grantType:i="refresh_token"}){var u;const a=new URLSearchParams,o={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(a.set("grant_type",i),a.set("refresh_token",e),n==="basic"){const h=Te.encode(`${t.clientId}:${t.clientSecret}`);o.authorization=`Basic ${h}`}else a.set("client_id",t.clientId),a.set("client_secret",t.clientSecret);if(s)for(const[h,p]of Object.entries(s))a.set(h,p);const{data:d,error:c}=await R(r,{method:"POST",body:a,headers:o});if(c)throw c;const l={accessToken:d.access_token,refreshToken:d.refresh_token,tokenType:d.token_type,scopes:(u=d.scope)==null?void 0:u.split(" "),idToken:d.id_token};if(d.expires_in){const h=new Date;l.accessTokenExpiresAt=new Date(h.getTime()+d.expires_in*1e3)}return l}function It(e){switch(e){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${e}`)}}function _r(...e){const t=e.map(It).join("");if(t.length===0)throw new Error("No valid characters provided for random string generation.");const r=t.length;return(n,...s)=>{if(n<=0)throw new Error("Length must be a positive integer.");let i=t,a=r;s.length>0&&(i=s.map(It).join(""),a=i.length);const o=new Uint8Array(n);yn(o);let d="";for(let c=0;c<n;c++){const l=o[c]%a;d+=i[l]}return d}}const Xe=_r("a-z","0-9","A-Z","-_"),et=["info","success","warn","error","debug"];function _s(e,t){return et.indexOf(t)<=et.indexOf(e)}const K={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",fg:{red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m"}},Ss={info:K.fg.blue,success:K.fg.green,warn:K.fg.yellow,error:K.fg.red,debug:K.fg.magenta},Ts=(e,t)=>{const r=new Date().toISOString();return`${K.dim}${r}${K.reset} ${Ss[e]}${e.toUpperCase()}${K.reset} ${K.bright}[Better Auth]:${K.reset} ${t}`},Rs=e=>{const t="error",r=(n,s,i=[])=>{if(!_s(t,n))return;const a=Ts(n,s);{n==="error"?console.error(a,...i):n==="warn"?console.warn(a,...i):console.log(a,...i);return}};return Object.fromEntries(et.map(n=>[n,(...[s,...i])=>r(n,s,i)]))},ie=Rs(),Us=e=>{const t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:r,scopes:n,redirectURI:s}){const i=e.disableDefaultScope?[]:["email","name"];return e.scope&&i.push(...e.scope),n&&i.push(...n),await $({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:i,state:r,redirectURI:s,responseMode:"form_post"})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:s})=>N({code:r,codeVerifier:n,redirectURI:s,options:e,tokenEndpoint:t}),async verifyIdToken(r,n){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,n);const s=bs(r),{kid:i,alg:a}=s;if(!i||!a)return!1;const o=await ks(i),{payload:d}=await ct(r,o,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.appBundleIdentifier||e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),n&&d.nonce!==n?!1:!!d},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>P({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://appleid.apple.com/auth/token"}),async getUserInfo(r){var a,o,d;if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;const n=Re(r.idToken);if(!n)return null;const s=r.user?`${(a=r.user.name)==null?void 0:a.firstName} ${(o=r.user.name)==null?void 0:o.lastName}`:n.name||n.email,i=await((d=e.mapProfileToUser)==null?void 0:d.call(e,n));return{user:{id:n.sub,name:s,emailVerified:!1,email:n.email,...i},data:n}},options:e}},ks=async e=>{const t="https://appleid.apple.com",r="/auth/keys",{data:n}=await R(`${t}${r}`);
1if(!(n!=null&&n.keys))throw new m("BAD_REQUEST",{message:"Keys not found"});const s=n.keys.find(i=>i.kid===e);if(!s)throw new Error(`JWK with kid ${e} not found`);return await at(s,s.alg)},Is=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){const s=e.disableDefaultScope?[]:["identify","email"];return r&&s.push(...r),e.scope&&s.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${s.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>N({code:t,redirectURI:r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){var i;if(e.getUserInfo)return e.getUserInfo(t);const{data:r,error:n}=await R("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;if(r.avatar===null){const a=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${a}.png`}else{const a=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${a}`}const s=await((i=e.mapProfileToUser)==null?void 0:i.call(e,r));return{user:{id:r.id,name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...s},data:r}},options:e}),vs=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:n,loginHint:s}){const i=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),await $({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:n,loginHint:s,additionalParams:e.configId?{config_id:e.configId}:{}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>N({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);if(t.split(".").length)try{const{payload:n}=await ct(t,Es(new URL("https://www.facebook.com/.well-known/oauth/openid/jwks")),{algorithms:["RS256"],audience:e.clientId,issuer:"https://www.facebook.com"});return r&&n.nonce!==r?!1:!!n}catch{return!1}return!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v18.0/oauth/access_token"}),async getUserInfo(t){var a,o;if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken){const d=Re(t.idToken),c={id:d.sub,name:d.name,email:d.email,picture:{data:{url:d.picture,height:100,width:100,is_silhouette:!1}}},l=await((a=e.mapProfileToUser)==null?void 0:a.call(e,{...c,email_verified:!0}));return{user:{...c,emailVerified:!0,...l},data:d}}const r=["id","name","email","picture",...(e==null?void 0:e.fields)||[]],{data:n,error:s}=await R("https://graph.facebook.com/me?fields="+r.join(","),{auth:{type:"Bearer",token:t.accessToken}});if(s)return null;const i=await((o=e.mapProfileToUser)==null?void 0:o.call(e,n));return{user:{id:n.id,name:n.name,email:n.email,image:n.picture.data.url,emailVerified:n.email_verified,...i},data:n}},options:e}),Os=e=>{const t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:n,loginHint:s,redirectURI:i}){const a=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&a.push(...e.scope),n&&a.push(...n),$({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i,loginHint:s})},validateAuthorizationCode:async({code:r,redirectURI:n})=>N({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>P({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://github.com/login/oauth/token"}),async getUserInfo(r){var d,c,l;if(e.getUserInfo)return e.getUserInfo(r);const{data:n,error:s}=await R("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(s)return null;const{data:i}=await R("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});!n.email&&i&&(n.email=(d=i.find(u=>u.primary)??i[0])==null?void 0:d.email);const a=((c=i==null?void 0:i.find(u=>
1u.email===n.email))==null?void 0:c.verified)??!1,o=await((l=e.mapProfileToUser)==null?void 0:l.call(e,n));return{user:{id:n.id.toString(),name:n.name||n.login,email:n.email,image:n.avatar_url,emailVerified:a,...o},data:n}},options:e}},Ds=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:s,loginHint:i,display:a}){if(!e.clientId||!e.clientSecret)throw ie.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new Ae("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new Ae("codeVerifier is required for Google");const o=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&o.push(...e.scope),r&&o.push(...r),await $({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:o,state:t,codeVerifier:n,redirectURI:s,prompt:e.prompt,accessType:e.accessType,display:a||e.display,loginHint:i,hd:e.hd})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>N({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://www.googleapis.com/oauth2/v4/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);const n=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:s}=await R(n);return s?s.aud===e.clientId&&(s.iss==="https://accounts.google.com"||s.iss==="accounts.google.com"):!1},async getUserInfo(t){var s;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;const r=Re(t.idToken),n=await((s=e.mapProfileToUser)==null?void 0:s.call(e,r));return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}},options:e}),Ls=e=>{const t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,n=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(s){const i=e.disableDefaultScope?[]:["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),s.scopes&&i.push(...i),$({id:"microsoft",options:e,authorizationEndpoint:r,state:s.state,codeVerifier:s.codeVerifier,scopes:i,redirectURI:s.redirectURI,prompt:e.prompt})},validateAuthorizationCode({code:s,codeVerifier:i,redirectURI:a}){return N({code:s,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:n})},async getUserInfo(s){var d;if(e.getUserInfo)return e.getUserInfo(s);if(!s.idToken)return null;const i=Re(s.idToken),a=e.profilePhotoSize||48;await R(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${s.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{const u=await c.response.clone().arrayBuffer(),h=xe.encode(u);i.picture=`data:image/jpeg;base64, ${h}`}catch(l){ie.error(l&&typeof l=="object"&&"name"in l?l.name:"",l)}}});const o=await((d=e.mapProfileToUser)==null?void 0:d.call(e,i));return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...o},data:i}},options:e}},Ns=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:s}){const i=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&i.push(...e.scope),r&&i.push(...r),$({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:n,redirectURI:s})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>N({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){var i,a;if(e.getUserInfo)return e.getUserInfo(t);const{data:r,error:n}=await R("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;const s=await((i=e.mapProfileToUser)==null?void 0:i.call(e,r));return{user:{id:r.id,name:r.display_name,email:r.email,image:(a=r.images[0])==null?void 0:a.url,emailVerified:!1,...s},data:r}},options:e}),Ps=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){const s=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&s.push(...e.scope),r&&s.push(...r),$({id:"twitch",redirectURI:n,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:s,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>N({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){var i;if(e.getUserInfo)return e.getUserInfo(t);const r=t.idToken;if(!r)return ie.error("No idToken found in token"),null;const n=Re(r),s=await((i=e.mapProfileToUser)==null?void 0:i.call(e,n));return{user:{id:n.sub,name:n.preferred_username,email:n.email,image:n.picture,emailVerified:!1,...s},data:n}},options:e}),Cs=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){const r=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),$({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>N({code:t,codeVerifier:r,authentication:"basic",redirectURI:n,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.twitter.com/2/oauth2/token"}),async getUserInfo(t){var o,d;if(e.getUserInfo)return e.getUserInfo(t);const{data:r,error:n}=await R("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;const{data:s,error:i}=await R("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});!i&&((o=s==null?void 0:s.data)!=null&&o.confirmed_email)&&(r.data.email=s.data.confirmed_email);const a=await((d=e.mapProfileToUser)==null?void 0:d.call(e,r));return{user:{id:r.data.id,name:r.data.name,email:r.data.email||r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...a},data:r}},options:e}),$s=e=>{const t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:n,codeVerifier:s,redirectURI:i})=>{const a=e.disableDefaultScope?[]:["account_info.read"];return e.scope&&a.push(...e.scope),n&&a.push(...n),await $({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:s})=>await N({code:r,codeVerifier:n,redirectURI:s,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>P({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.dropbox.com/oauth2/token"}),async getUserInfo(r){var a,o;if(e.getUserInfo)return e.getUserInfo(r);const{data:n,error:s}=await R("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(s)return null;const i=await((a=e.mapProfileToUser)==null?void 0:a.call(e,n));return{user:{id:n.account_id,name:(o=n.name)==null?void 0:o.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...i},data:n}},options:e}},Vs=e=>{const t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:n,scopes:s,redirectURI:i,loginHint:a})=>{const o=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&o.push(...e.scope),s&&o.push(...s),await $({id:"linkedin",options:e,authorizationEndpoint:t,scopes:o,state:n,loginHint:a,redirectURI:i})},validateAuthorizationCode:async({code:n,redirectURI:s})=>await N({code:n,redirectURI:s,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>P({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(n){var o;if(e.getUserInfo)return e.getUserInfo(n);const{data:s,error:i}=await R("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;const a=await((o=e.mapProfileToUser)==null?void 0:o.call(e,s));return{user:{id:s.sub,name:s.name,email:s.email,emailVerified:s.email_verified||!1,image:s.picture,...a},data:s}},options:e}},Je=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),xs=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Je(`${t}/oauth/authorize`),tokenEndpoint:Je(`${t}/oauth/token`),userinfoEndpoint:Je(`${t}/api/v4/user`)}},js=e=>{const{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:n}=xs(e.issuer),s="gitlab";return{id:s,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:o,codeVerifier:d,loginHint:c,redirectURI:l})=>{const u=e.disableDefaultScope?[]:["read_user"];return e.scope&&u.push(...e.scope),o&&u.push(...o),await $({id:s,options:e,authorizationEndpoint:t,scopes:u,state:a,redirectURI:l,codeVerifier:d,loginHint:c})},validateAuthorizationCode:async({code:a,redirectURI:o,codeVerifier:d})=>N({code:a,redirectURI:o,options:e,codeVerifier:d,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async a=>P({refreshToken:a,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://gitlab.com/oauth/token"}),async getUserInfo(a){var l;if(e.getUserInfo)return e.getUserInfo(a);const{data:o,error:d}=await R(n,{headers:{authorization:`Bearer ${a.accessToken}`}});if(d||o.state!=="active"||o.locked)return null;
1const c=await((l=e.mapProfileToUser)==null?void 0:l.call(e,o));return{user:{id:o.id.toString(),name:o.name??o.username,email:o.email,image:o.avatar_url,emailVerified:!0,...c},data:o}},options:e}},Ws=e=>({id:"tiktok",name:"TikTok",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){const s=e.disableDefaultScope?[]:["user.info.profile"];return e.scope&&s.push(...e.scope),r&&s.push(...r),new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${s.join(",")}&response_type=code&client_key=${e.clientKey}&client_secret=${e.clientSecret}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>N({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);const r=["open_id","avatar_large_url","display_name","username"],{data:n,error:s}=await R(`https://open.tiktokapis.com/v2/user/info/?fields=${r.join(",")}`,{headers:{authorization:`Bearer ${t.accessToken}`}});return s?null:{user:{email:n.data.user.email||n.data.user.username,id:n.data.user.open_id,name:n.data.user.display_name||n.data.user.username,image:n.data.user.avatar_large_url,emailVerified:!!n.data.user.email},data:n}},options:e}),qs=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){const s=e.disableDefaultScope?[]:["identity"];return e.scope&&s.push(...e.scope),r&&s.push(...r),$({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:s,state:t,redirectURI:n,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{const n=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),s={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${xe.encode(`${e.clientId}:${e.clientSecret}`)}`},{data:i,error:a}=await R("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:s,body:n.toString()});if(a)throw a;return Ar(i)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://www.reddit.com/api/v1/access_token"}),async getUserInfo(t){var i,a;if(e.getUserInfo)return e.getUserInfo(t);const{data:r,error:n}=await R("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(n)return null;const s=await((i=e.mapProfileToUser)==null?void 0:i.call(e,r));return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:(a=r.icon_img)==null?void 0:a.split("?")[0],...s},data:r}},options:e}),Hs=e=>({id:"roblox",name:"Roblox",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){const s=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&s.push(...e.scope),r&&s.push(...r),new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${s.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"select_account+consent"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>N({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://apis.roblox.com/oauth/v1/token",authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://apis.roblox.com/oauth/v1/token"}),async getUserInfo(t){var i;if(e.getUserInfo)return e.getUserInfo(t);const{data:r,error:n}=await R("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;const s=await((i=e.mapProfileToUser)==null?void 0:i.call(e,r));return{user:{id:r.sub,name:r.nickname||r.preferred_username||"",image:r.picture,email:r.preferred_username||null,emailVerified:!0,...s},data:{...r}}},options:e}),Ms=e=>({id:"vk",name:"VK",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:s}){const i=e.disableDefaultScope?[]:["email","phone"];return e.scope&&i.push(...e.scope),r&&i.push(...r),$({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:i,state:t,redirectURI:s,codeVerifier:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n,deviceId:s})=>N({code:t,codeVerifier:r,redirectURI:e.redirectURI||n,options:e,deviceId:s,tokenEndpoint:"https://id.vk.com/oauth2/auth"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>P({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://id.vk.com/oauth2/auth"}),async getUserInfo(t){var a;if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;
1const r=new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString(),{data:n,error:s}=await R("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(s||!n.user.email)return null;const i=await((a=e.mapProfileToUser)==null?void 0:a.call(e,n));return{user:{id:n.user.user_id,first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!!n.user.email,birthday:n.user.birthday,sex:n.user.sex,...i},data:n}},options:e}),Bs=e=>({id:"kick",name:"Kick",createAuthorizationURL({state:t,scopes:r,redirectURI:n,codeVerifier:s}){const i=e.disableDefaultScope?[]:["user:read"];return e.scope&&i.push(...e.scope),r&&i.push(...r),$({id:"kick",redirectURI:n,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:i,codeVerifier:s,state:t})},async validateAuthorizationCode({code:t,redirectURI:r,codeVerifier:n}){return N({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:n})},async getUserInfo(t){var a;if(e.getUserInfo)return e.getUserInfo(t);const{data:r,error:n}=await R("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;const s=r.data[0],i=await((a=e.mapProfileToUser)==null?void 0:a.call(e,s));return{user:{id:s.user_id,name:s.name,email:s.email,image:s.profile_picture,emailVerified:!0,...i},data:s}},options:e}),Js=e=>{const t={pkce:!0,...e};return{id:"zoom",name:"Zoom",createAuthorizationURL:async({state:r,redirectURI:n,codeVerifier:s})=>{const i=new URLSearchParams({response_type:"code",redirect_uri:t.redirectURI?t.redirectURI:n,client_id:t.clientId,state:r});if(t.pkce){const o=await br(s);i.set("code_challenge_method","S256"),i.set("code_challenge",o)}const a=new URL("https://zoom.us/oauth/authorize");return a.search=i.toString(),a},validateAuthorizationCode:async({code:r,redirectURI:n,codeVerifier:s})=>N({code:r,redirectURI:t.redirectURI||n,codeVerifier:s,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),async getUserInfo(r){var a;if(t.getUserInfo)return t.getUserInfo(r);const{data:n,error:s}=await R("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(s)return null;const i=await((a=t.mapProfileToUser)==null?void 0:a.call(t,n));return{user:{id:n.id,name:n.display_name,image:n.pic_url,email:n.email,emailVerified:!!n.verified,...i},data:{...n}}}}},Ks={apple:Us,discord:Is,facebook:vs,github:Os,microsoft:Ls,google:Ds,spotify:Ns,twitch:Ps,twitter:Cs,dropbox:$s,kick:Bs,linkedin:Vs,gitlab:js,tiktok:Ws,reddit:qs,roblox:Hs,vk:Ms,zoom:Js},Sr=Object.keys(Ks),zs=f.enum(Sr,{description:"OAuth2 provider to use"});async function Tr(e,t){var d,c,l,u;const r=((d=e.body)==null?void 0:d.callbackURL)||e.context.options.baseURL;if(!r)throw new m("BAD_REQUEST",{message:"callbackURL is required"});const n=Xe(128),s=Xe(32),i=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:(c=e.body)==null?void 0:c.errorCallbackURL,newUserURL:(l=e.body)==null?void 0:l.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3,requestSignUp:(u=e.body)==null?void 0:u.requestSignUp}),a=new Date;a.setMinutes(a.getMinutes()+10);const o=await e.context.internalAdapter.createVerificationValue({value:i,identifier:s,expiresAt:a});if(!o)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new m("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:o.identifier,codeVerifier:n}}async function Fs(e){const t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);const n=f.object({callbackURL:f.string(),codeVerifier:f.string(),errorURL:f.string().optional(),newUserURL:f.string().optional(),expiresAt:f.number(),link:f.object({email:f.string(),userId:f.coerce.string()}).optional(),requestSignUp:f.boolean().optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}
1/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}const Zs=e=>_r("a-z","A-Z","0-9")(e);f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.coerce.string(),accessToken:f.string().nullish(),refreshToken:f.string().nullish(),idToken:f.string().nullish(),accessTokenExpiresAt:f.date().nullish(),refreshTokenExpiresAt:f.date().nullish(),scope:f.string().nullish(),password:f.string().nullish(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date)});f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().nullish(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date)});f.object({id:f.string(),userId:f.coerce.string(),expiresAt:f.date(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date),token:f.string(),ipAddress:f.string().nullish(),userAgent:f.string().nullish()});f.object({id:f.string(),value:f.string(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date),expiresAt:f.date(),identifier:f.string()});function Gs(e,t){var r,n,s;if(!t)return e;for(const i in t){const a=(r=t[i])==null?void 0:r.modelName;a&&(e[i].modelName=a);for(const o in e[i].fields){const d=(s=(n=t[i])==null?void 0:n.fields)==null?void 0:s[o];d&&(e[i].fields[o].fieldName=d)}}return e}async function Qs(e,t,r=3600){return await new ls(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}const Ke=new Map,Ys=new TextEncoder,Xs={decode:(e,t="utf-8")=>(Ke.has(t)||Ke.set(t,new TextDecoder(t)),Ke.get(t).decode(e)),encode:Ys.encode},Rr=he(async()=>({})),oe=he.create({use:[Rr,he(async()=>({}))]}),U=Ze.create({use:[Rr]});function tt(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function ei(e){let t="";for(let r=0;r<e.length;r++)t+=tt(e[r]);return t}function Ur(e,t=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${Ur(l,t)}$`).join("|")})`;let r="",n="",s=".";t===!0?(r="/",n="[/\\\\]",s="[^/\\\\]"):t&&(r=t,n=ei(r),n.length>1?(n=`(?:${n})`,s=`((?!${n}).)`):s=`[^${n}]`);let i=t?`${n}+?`:"",a=t?`${n}*?`:"",o=t?e.split(r):[e],d="";for(let c=0;c<o.length;c++){let l=o[c],u=o[c+1],h="";if(!(!l&&c>0)){if(t&&(c===o.length-1?h=a:u!=="**"?h=i:h=""),t&&l==="**"){h&&(d+=c===0?"":h,d+=`(?:${s}*?${h})*?`);continue}for(let p=0;p<l.length;p++){let w=l[p];w==="\\"?p<l.length-1&&(d+=tt(l[p+1]),p++):w==="?"?d+=s:w==="*"?d+=`${s}*?`:d+=tt(w)}d+=h}}return d}function ti(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function kr(e,t){if(typeof e!="string"&&!Array.isArray(e))throw new 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&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=Ur(e,t.separator),n=new RegExp(`^${r}$`,t.flags),s=ti.bind(null,n);return s.options=t,s.pattern=e,s.regexp=n,s}oe(async e=>{var p,w,A,y,_,g,T;if(((p=e.request)==null?void 0:p.method)!=="POST"||!e.request)return;const{body:t,query:r,context:n}=e,s=((w=e.headers)==null?void 0:w.get("origin"))||((A=e.headers)==null?void 0:A.get("referer"))||"",i=(t==null?void 0:t.callbackURL)||(r==null?void 0:r.callbackURL),a=t==null?void 0:t.redirectTo,o=t==null?void 0:t.errorCallbackURL,d=t==null?void 0:t.newUserCallbackURL,c=Array.isArray(n.options.trustedOrigins)?n.trustedOrigins:[...n.trustedOrigins,...await((_=(y=n.options).trustedOrigins)==null?void 0:_.call(y,e.request))||[]],l=(g=e.headers)==null?void 0:g.has("cookie"),u=(E,k)=>{if(E.startsWith("/"))return!1;if(k.includes("*"))return kr(k)(Jt(E));const S=Sn(E);return S==="http:"||S==="https:"||!S?k===_n(E):E.startsWith(k)},h=(E,k)=>{if(!E)return;if(!c.some(G=>u(E,G)||(E==null?void 0:E.startsWith("/"))&&k!=="origin"&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/]*(?:\?[\w\-.\+/=&%]*)?$/.test(E)))throw e.context.logger.error(`Invalid ${k}: ${E}`),e.context.logger.info(`If it's a valid URL, please add ${E} to trustedOrigins in your auth config 2`,`Current list of trustedOrigins: ${c}`),new m("FORBIDDEN",{message:`Invalid ${k}`})};l&&!((T=e.context.options.advanced)!=null&&T.disableCSRFCheck)&&h(s,"origin"),i&&h(i,"callbackURL"),a&&h(a,"redirectURL"),o&&h(o,"errorCallbackURL"),d&&h(d,"newUserCallbackURL")});const dt=e=>oe(async t=>{var d,c;if(!t.request)return;const{context:r}=t,n=e(t),s=Array.isArray(r.options.trustedOrigins)?r.trustedOrigins:[...r.trustedOrigins,...await((c=(d=r.options).trustedOrigins)==null?void 0:c.call(
2d,t.request))||[]],i=(l,u)=>l.startsWith("/")?!1:u.includes("*")?kr(u)(Jt(l)):l.startsWith(u),a=(l,u)=>{if(!l)return;if(!s.some(p=>i(l,p)||(l==null?void 0:l.startsWith("/"))&&u!=="origin"&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/]*(?:\?[\w\-.\+/=&%]*)?$/.test(l)))throw t.context.logger.error(`Invalid ${u}: ${l}`),t.context.logger.info(`If it's a valid URL, please add ${l} to trustedOrigins in your auth config 3`,`Current list of trustedOrigins: ${s}`),new m("FORBIDDEN",{message:`Invalid ${u}`})},o=Array.isArray(n)?n:[n];for(const l of o)a(l,"callbackURL")}),lt={isAction:!1},b={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",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",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"},ri=()=>U("/get-session",{method:"GET",query:f.optional(f.object({disableCookieCache:f.optional(f.boolean({description:"Disable cookie cache and fetch session from database"}).or(f.string().transform(e=>e==="true"))).optional(),disableRefresh:f.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).or(f.string().transform(e=>e==="true")).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async e=>{var t,r,n,s,i,a;try{const o=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!o)return null;const d=e.getCookie(e.context.authCookies.sessionData.name),c=d?Bt(Xs.decode(xe.decode(d))):null;if(c&&!await Mt("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...c.session,expiresAt:c.expiresAt}),c.signature)){const _=e.context.authCookies.sessionData.name;e.setCookie(_,"",{maxAge:0})}const l=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(c!=null&&c.session&&((r=(t=e.context.options.session)==null?void 0:t.cookieCache)!=null&&r.enabled)&&!((n=e.query)!=null&&n.disableCookieCache)){const y=c.session;if(c.expiresAt<Date.now()||y.session.expiresAt<new Date){const g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(y)}const u=await e.context.internalAdapter.findSession(o);if(e.context.session=u,!u||u.session.expiresAt<new Date)return pe(e),u&&await e.context.internalAdapter.deleteSession(u.session.token),e.json(null);if(l||(s=e.query)!=null&&s.disableRefresh)return e.json(u);const h=e.context.sessionConfig.expiresIn,p=e.context.sessionConfig.updateAge;if(u.session.expiresAt.valueOf()-h*1e3+p*1e3<=Date.now()&&(!((i=e.query)!=null&&i.disableRefresh)||!((a=e.context.options.session)!=null&&a.disableSessionRefresh))){const y=await e.context.internalAdapter.updateSession(u.session.token,{expiresAt:_e(e.context.sessionConfig.expiresIn,"sec")});if(!y)return pe(e),e.json(null,{status:401});const _=(y.expiresAt.valueOf()-Date.now())/1e3;return await Z(e,{session:y,user:u.user},!1,{maxAge:_}),e.json({session:y,user:u.user})}return await Kt(e,u),e.json(u)}catch(o){throw e.context.logger.error("INTERNAL_SERVER_ERROR",o),new m("INTERNAL_SERVER_ERROR",{message:b.FAILED_TO_GET_SESSION})}}),ce=async(e,t)=>{if(e.context.session)return e.context.session;const r=await ri()({...e,asResponse:!1,headers:e.headers,returnHeaders:!1,query:{...t,...e.query}}).catch(n=>null);return e.context.session=r,r},Q=oe(async e=>{const t=await ce(e);
3if(!(t!=null&&t.session))throw new m("UNAUTHORIZED");return{session:t}});oe(async e=>{const t=await ce(e);if(!(t!=null&&t.session)&&(e.request||e.headers))throw new m("UNAUTHORIZED");return{session:t}});const ni=oe(async e=>{var a;const t=await ce(e);if(!(t!=null&&t.session))throw new m("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};const r=e.context.sessionConfig.freshAge,n=((a=t.session.updatedAt)==null?void 0:a.valueOf())||t.session.createdAt.valueOf();if(!(Date.now()-n<r*1e3))throw new m("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});U("/revoke-session",{method:"POST",body:f.object({token:f.string({description:"The token to revoke"})}),use:[Q],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=>{const t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new m("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new m("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(n){throw e.context.logger.error(n&&typeof n=="object"&&"name"in n?n.name:"",n),new m("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});U("/revoke-sessions",{method:"POST",use:[Q],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.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new m("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});U("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[Q],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=>{const t=e.context.session;if(!t.user)throw new m("UNAUTHORIZED");const s=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(s.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function me(e,t,r,n=3600){return await Qs({email:t.toLowerCase(),updateTo:r},e,n)}async function Ir(e,t){var s,i;if(!((s=e.context.options.emailVerification)!=null&&s.sendVerificationEmail))throw e.context.logger.error("Verification email isn't enabled."),new m("BAD_REQUEST",{message:"Verification email isn't enabled"});const r=await me(e.context.secret,t.email,void 0,(i=e.context.options.emailVerification)==null?void 0:i.expiresIn),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:n,token:r},e.request)}U("/send-verification-email",{method:"POST",body:f.object({email:f.string({description:"The email to send the verification email to"}).email(),callbackURL:f.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{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:"[email protected]"},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=>{var n;if(!((n=e.context.options.emailVerification)!=null&&n.sendVerificationEmail))throw e.context.logger.error("Verification email isn't enabled."),new m("BAD_REQUEST",{message:"Verification email isn't enabled"});const{email:t}
3=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new m("BAD_REQUEST",{message:b.USER_NOT_FOUND});return await Ir(e,r.user),e.json({status:!0})});U("/verify-email",{method:"GET",query:f.object({token:f.string({description:"The token to verify the email"}),callbackURL:f.string({description:"The URL to redirect to after email verification"}).optional()}),use:[dt(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",properties:{id:{type:"string",description:"User ID"},email:{type:"string",description:"User email"},name:{type:"string",description:"User name"},image:{type:"string",description:"User image URL"},emailVerified:{type:"boolean",description:"Indicates if the user email is verified"},createdAt:{type:"string",description:"User creation date"},updatedAt:{type:"string",description:"User update date"}},required:["id","email","name","image","emailVerified","createdAt","updatedAt"]},status:{type:"boolean",description:"Indicates if the email was verified successfully"},required:["user","status"]}}}}}}}}},async e=>{var o,d,c,l,u;function t(h){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${h}`):e.redirect(`${e.query.callbackURL}?error=${h}`):new m("UNAUTHORIZED",{message:h})}const{token:r}=e.query;let n;try{n=await ct(r,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(h){return h instanceof Ce?t("token_expired"):t("invalid_token")}const i=f.object({email:f.string().email(),updateTo:f.string().optional()}).parse(n.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t("user_not_found");if(i.updateTo){const h=await ce(e);if(!h){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(h.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}const p=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1},e),w=await me(e.context.secret,i.updateTo);if(await((d=(o=e.context.options.emailVerification)==null?void 0:o.sendVerificationEmail)==null?void 0:d.call(o,{user:p,url:`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${e.query.callbackURL||"/"}`,token:w},e.request)),await Z(e,{session:h.session,user:{...h.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:{id:p.id,email:p.email,name:p.name,image:p.image,emailVerified:p.emailVerified,createdAt:p.createdAt,updatedAt:p.updatedAt}})}if(await((l=(c=e.context.options.emailVerification)==null?void 0:c.onEmailVerification)==null?void 0:l.call(c,a.user,e.request)),await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0},e),(u=e.context.options.emailVerification)!=null&&u.autoSignInAfterVerification){const h=await ce(e);if(!h||h.user.email!==i.email){const p=await e.context.internalAdapter.createSession(a.user.id,e.headers);if(!p)throw new m("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await Z(e,{session:p,user:{...a.user,emailVerified:!0}})}else await Z(e,{session:h.session,user:{...h.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function vr(e,{userInfo:t,account:r,callbackURL:n,disableSignUp:s,overrideUserInfo:i}){var l,u,h,p,w,A,y,_;const a=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(g=>{throw ie.error(`Better auth was unable to query your database. 4Error: `,g),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)});let o=a==null?void 0:a.user,d=!o;if(a){const g=a.accounts.find(T=>T.providerId===r.providerId);if(g){const T=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope}).filter(([E,k])=>k!==void 0));Object.keys(T).length>
40&&await e.context.internalAdapter.updateAccount(g.id,T,e)}else{const T=(u=(l=e.context.options.account)==null?void 0:l.accountLinking)==null?void 0:u.trustedProviders;if(!(T==null?void 0:T.includes(r.providerId))&&!t.emailVerified||((p=(h=e.context.options.account)==null?void 0:h.accountLinking)==null?void 0:p.enabled)===!1)return ln&&ie.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{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:a.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope},e)}catch(k){return ie.error("Unable to link account",k),{error:"unable to link account",data:null}}}i&&await e.context.internalAdapter.updateUser(a.user.id,{...t,email:t.email.toLowerCase(),emailVerified:t.email.toLocaleLowerCase()===a.user.email&&a.user.emailVerified||t.emailVerified})}else{if(s)return{error:"signup disabled",data:null,isRegister:!1};try{const{id:g,...T}=t;if(o=await e.context.internalAdapter.createOAuthUser({...T,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()},e).then(E=>E==null?void 0:E.user),!t.emailVerified&&o&&((w=e.context.options.emailVerification)!=null&&w.sendOnSignUp)){const E=await me(e.context.secret,o.email,void 0,(A=e.context.options.emailVerification)==null?void 0:A.expiresIn),k=`${e.context.baseURL}/verify-email?token=${E}&callbackURL=${n}`;await((_=(y=e.context.options.emailVerification)==null?void 0:y.sendVerificationEmail)==null?void 0:_.call(y,{user:o,url:k,token:E},e.request))}}catch(g){return ie.error(g),g instanceof m?{error:g.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}}if(!o)return{error:"unable to create user",data:null,isRegister:!1};const c=await e.context.internalAdapter.createSession(o.id,e.headers);return c?{data:{session:c,user:o},error:null,isRegister:d}:{error:"unable to create session",data:null,isRegister:!1}}U("/sign-in/social",{method:"POST",body:f.object({callbackURL:f.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:f.string().optional(),errorCallbackURL:f.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:zs,disableRedirect:f.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:f.optional(f.object({token:f.string({description:"ID token from the provider"}),nonce:f.string({description:"Nonce used to generate the token"}).optional(),accessToken:f.string({description:"Access token from the provider"}).optional(),refreshToken:f.string({description:"Refresh token from the provider"}).optional(),expiresAt:f.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"}),scopes:f.array(f.string(),{description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:f.boolean({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:f.string({description:"The login hint to use for the authorization code request"}).optional()}),metadata:{openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",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:"null",nullable:!0},user:{type:"object",properties:{id:{type:"string"},email:{type:"string"},name:{type:"string",nullable:!0},image:{type:"string",nullable:!0},emailVerified:{type:"boolean"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","email","emailVerified","createdAt","updatedAt"]}},required:["redirect","token","user"]}}}}}}}}},async e=>{var i,a;const t=e.context.socialProviders.find(o=>o.id===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}),new m("NOT_FOUND",{message:b.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new m("NOT_FOUND",{message:b.ID_TOKEN_NOT_SUPPORTED});
4const{token:o,nonce:d}=e.body.idToken;if(!await t.verifyIdToken(o,d))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new m("UNAUTHORIZED",{message:b.INVALID_TOKEN});const l=await t.getUserInfo({idToken:o,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!l||!(l!=null&&l.user))throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new m("UNAUTHORIZED",{message:b.FAILED_TO_GET_USER_INFO});const u=await((a=(i=t.options)==null?void 0:i.mapProfileToUser)==null?void 0:a.call(i,l.user)),h={...l.user,...u};if(!h.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new m("UNAUTHORIZED",{message:b.USER_EMAIL_NOT_FOUND});const p=await vr(e,{userInfo:{...h,email:h.email,id:h.id,name:h.name||"",image:h.image,emailVerified:h.emailVerified||!1},account:{providerId:t.id,accountId:l.user.id,accessToken:e.body.idToken.accessToken},disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp});if(p.error)throw new m("UNAUTHORIZED",{message:p.error});return await Z(e,p.data),e.json({redirect:!1,token:p.data.session.token,url:void 0,user:{id:p.data.user.id,email:p.data.user.email,name:p.data.user.name,image:p.data.user.image,emailVerified:p.data.user.emailVerified,createdAt:p.data.user.createdAt,updatedAt:p.data.user.updatedAt}})}const{codeVerifier:r,state:n}=await Tr(e),s=await t.createAuthorizationURL({state:n,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`,scopes:e.body.scopes,loginHint:e.body.loginHint});return e.json({url:s.toString(),redirect:!e.body.disableRedirect})});U("/sign-in/email",{method:"POST",body:f.object({email:f.string({description:"Email of the user"}),password:f.string({description:"Password of the user"}),callbackURL:f.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:f.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{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:"null",nullable:!0},user:{type:"object",properties:{id:{type:"string"},email:{type:"string"},name:{type:"string",nullable:!0},image:{type:"string",nullable:!0},emailVerified:{type:"boolean"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","email","emailVerified","createdAt","updatedAt"]}},required:["redirect","token","user"]}}}}}}}},async e=>{var c,l,u,h,p,w,A;if(!((l=(c=e.context.options)==null?void 0:c.emailAndPassword)!=null&&l.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!"),new m("BAD_REQUEST",{message:"Email and password is not enabled"});const{email:t,password:r}=e.body;if(!f.string().email().safeParse(t).success)throw new m("BAD_REQUEST",{message:b.INVALID_EMAIL});const s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new m("UNAUTHORIZED",{message:b.INVALID_EMAIL_OR_PASSWORD});const i=s.accounts.find(y=>y.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new m("UNAUTHORIZED",{message:b.INVALID_EMAIL_OR_PASSWORD});const a=i==null?void 0:i.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new m("UNAUTHORIZED",{message:b.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:a,password:r}))throw e.context.logger.error("Invalid password"),new m("UNAUTHORIZED",{message:b.INVALID_EMAIL_OR_PASSWORD});if((h=(u=e.context.options)==null?void 0:u.emailAndPassword)!=null&&h.requireEmailVerification&&!s.user.emailVerified){if(!((w=(p=e.context.options)==null?void 0:p.emailVerification)!=null&&w.sendVerificationEmail))throw new m
4("FORBIDDEN",{message:b.EMAIL_NOT_VERIFIED});const y=await me(e.context.secret,s.user.email,void 0,(A=e.context.options.emailVerification)==null?void 0:A.expiresIn),_=`${e.context.baseURL}/verify-email?token=${y}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:s.user,url:_,token:y},e.request),new m("FORBIDDEN",{message:b.EMAIL_NOT_VERIFIED})}const d=await e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new m("UNAUTHORIZED",{message:b.FAILED_TO_CREATE_SESSION});return await Z(e,{session:d,user:s.user},e.body.rememberMe===!1),e.json({redirect:!!e.body.callbackURL,token:d.token,url:e.body.callbackURL,user:{id:s.user.id,email:s.user.email,name:s.user.name,image:s.user.image,emailVerified:s.user.emailVerified,createdAt:s.user.createdAt,updatedAt:s.user.updatedAt}})});const Oe=f.object({code:f.string().optional(),error:f.string().optional(),device_id:f.string().optional(),error_description:f.string().optional(),state:f.string().optional(),user:f.string().optional()});U("/callback/:id",{method:["GET","POST"],body:Oe.optional(),query:Oe.optional(),metadata:lt},async e=>{var S,G,Ue,ne,we,de;let t;const r=((S=e.context.options.onAPIError)==null?void 0:S.errorURL)||`${e.context.baseURL}/error`;try{if(e.method==="GET")t=Oe.parse(e.query);else if(e.method==="POST")t=Oe.parse(e.body);else throw new Error("Unsupported method")}catch(O){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",O),e.redirect(`${r}?error=invalid_callback_request`)}const{code:n,error:s,state:i,error_description:a,device_id:o}=t;if(s)throw e.redirect(`${r}?error=${s}&error_description=${a}`);if(!i)throw e.context.logger.error("State not found",s),e.redirect(`${r}?error=state_not_found`);const{codeVerifier:d,callbackURL:c,link:l,errorURL:u,newUserURL:h,requestSignUp:p}=await Fs(e);function w(O){let I=u||r;throw I.includes("?")?I=`${I}&error=${O}`:I=`${I}?error=${O}`,e.redirect(I)}if(!n)throw e.context.logger.error("Code not found"),w("no_code");const A=e.context.socialProviders.find(O=>O.id===e.params.id);if(!A)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),w("oauth_provider_not_found");let y;try{y=await A.validateAuthorizationCode({code:n,codeVerifier:d,deviceId:o,redirectURI:`${e.context.baseURL}/callback/${A.id}`})}catch(O){throw e.context.logger.error("",O),w("invalid_code")}const _=await A.getUserInfo({...y,user:(G=e.body)!=null&&G.user?Bt(e.body.user):void 0}).then(O=>O==null?void 0:O.user);if(!_)return e.context.logger.error("Unable to get user info"),w("unable_to_get_user_info");if(!_.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),w("email_not_found");if(!c)throw e.context.logger.error("No callback URL found"),w("no_callback_url");if(l){const O=await e.context.internalAdapter.findAccount(_.id);if(O){if(O.userId.toString()!==l.userId.toString())return w("account_already_linked_to_different_user");const D=Object.fromEntries(Object.entries({accessToken:y.accessToken,idToken:y.idToken,refreshToken:y.refreshToken,accessTokenExpiresAt:y.accessTokenExpiresAt,refreshTokenExpiresAt:y.refreshTokenExpiresAt,scope:(Ue=y.scopes)==null?void 0:Ue.join(",")}).filter(([M,V])=>V!==void 0));await e.context.internalAdapter.updateAccount(O.id,D)}else if(!await e.context.internalAdapter.createAccount({userId:l.userId,providerId:A.id,accountId:_.id,...y,scope:(ne=y.scopes)==null?void 0:ne.join(",")},e))return w("unable_to_link_account");let I;try{I=c.toString()}catch{I=c}throw e.redirect(I)}const g=await vr(e,{userInfo:{..._,email:_.email,name:_.name||_.email},account:{providerId:A.id,accountId:_.id,...y,scope:(we=y.scopes)==null?void 0:we.join(",")},callbackURL:c,disableSignUp:A.disableImplicitSignUp&&!p||((de=A.options)==null?void 0:de.disableSignUp)});if(g.error)return e.context.logger.error(g.error.split(" ").join("_")),w(g.error.split(" ").join("_"));const{session:T,user:E}=g.data;await Z(e,{session:T,user:E});let k;try{k=(g.isRegister&&h||c).toString()}catch{k=g.isRegister&&h||c}throw e.redirect(k)});U("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);
4if(!t)throw pe(e),new m("BAD_REQUEST",{message:b.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),pe(e),e.json({success:!0})});function vt(e,t,r){const n=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([s,i])=>n.searchParams.set(s,i)),n.href}function si(e,t,r){const n=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([s,i])=>n.searchParams.set(s,i)),n.href}U("/forget-password",{method:"POST",body:f.object({email:f.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:f.string({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:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{var d;if(!((d=e.context.options.emailAndPassword)!=null&&d.sendResetPassword))throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),new m("BAD_REQUEST",{message:"Reset password isn't enabled"});const{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0});const s=60*60*1,i=_e(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||s,"sec"),a=Zs(24);await e.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`reset-password:${a}`,expiresAt:i});const o=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:n.user,url:o,token:a},e.request),e.json({status:!0})});U("/reset-password/:token",{method:"GET",query:f.object({callbackURL:f.string({description:"The URL to redirect the user to reset their password"})}),use:[dt(e=>e.query.callbackURL)],metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{const{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(vt(e.context,r,{error:"INVALID_TOKEN"}));const n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(vt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(si(e.context,r,{token:t}))});U("/reset-password",{method:"POST",query:f.object({token:f.string().optional()}).optional(),body:f.object({newPassword:f.string({description:"The new password to set"}),token:f.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{var u,h,p;const t=e.body.token||((u=e.query)==null?void 0:u.token);if(!t)throw new m("BAD_REQUEST",{message:b.INVALID_TOKEN});const{newPassword:r}=e.body,n=(h=e.context.password)==null?void 0:h.config.minPasswordLength,s=(p=e.context.password)==null?void 0:p.config.maxPasswordLength;if(r.length<n)throw new m("BAD_REQUEST",{message:b.PASSWORD_TOO_SHORT});if(r.length>s)throw new m("BAD_REQUEST",{message:b.PASSWORD_TOO_LONG});const i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw new m("BAD_REQUEST",{message:b.INVALID_TOKEN});const o=a.value,d=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(o)).find(w=>w.providerId==="credential")?(await e.context.internalAdapter.updatePassword(o,d,e),await e.context.internalAdapter.deleteVerificationValue(a.id),e.json({status:!0}
4)):(await e.context.internalAdapter.createAccount({userId:o,providerId:"credential",password:d,accountId:o},e),await e.context.internalAdapter.deleteVerificationValue(a.id),e.json({status:!0}))});U("/change-password",{method:"POST",body:f.object({newPassword:f.string({description:"The new password to set"}),currentPassword:f.string({description:"The current password"}),revokeOtherSessions:f.boolean({description:"Revoke all other sessions"}).optional()}),use:[Q],metadata:{openapi:{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=>{const{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,s=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new m("BAD_REQUEST",{message:b.PASSWORD_TOO_SHORT});const a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new m("BAD_REQUEST",{message:b.PASSWORD_TOO_LONG});const d=(await e.context.internalAdapter.findAccounts(s.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!d||!d.password)throw new m("BAD_REQUEST",{message:b.CREDENTIAL_ACCOUNT_NOT_FOUND});const c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:d.password,password:r}))throw new m("BAD_REQUEST",{message:b.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(d.id,{password:c});let u=null;if(n){await e.context.internalAdapter.deleteSessions(s.user.id);const h=await e.context.internalAdapter.createSession(s.user.id,e.headers);if(!h)throw new m("INTERNAL_SERVER_ERROR",{message:b.FAILED_TO_GET_SESSION});await Z(e,{session:h,user:s.user}),u=h.token}return e.json({token:u,user:{id:s.user.id,email:s.user.email,name:s.user.name,image:s.user.image,emailVerified:s.user.emailVerified,createdAt:s.user.createdAt,updatedAt:s.user.updatedAt}})});U("/set-password",{method:"POST",body:f.object({newPassword:f.string()}),metadata:{SERVER_ONLY:!0},use:[Q]},async e=>{const{newPassword:t}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new m("BAD_REQUEST",{message:b.PASSWORD_TOO_SHORT});const s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new m("BAD_REQUEST",{message:b.PASSWORD_TOO_LONG});const a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),o=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:o},e),e.json({status:!0});throw new m("BAD_REQUEST",{message:"user already has a password"})});U("/delete-user",{method:"POST",use:[Q],body:f.object({callbackURL:f.string().optional(),password:f.string().optional(),token:f.string().optional()}),metadata:{openapi:{description:"Delete the user",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=>{var s,i,a,o,d,c,l;if(!((i=(s=e.context.options.user)==null?void 0:s.deleteUser)!=null&&i.enabled))throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new m("NOT_FOUND");const t=e.context.session;
4if(e.body.password){const h=(await e.context.internalAdapter.findAccounts(t.user.id)).find(w=>w.providerId==="credential"&&w.password);if(!h||!h.password)throw new m("BAD_REQUEST",{message:b.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:h.password,password:e.body.password}))throw new m("BAD_REQUEST",{message:b.INVALID_PASSWORD})}else if((a=e.context.options.session)!=null&&a.freshAge){const u=t.session.createdAt.getTime(),h=e.context.options.session.freshAge;if(Date.now()-u>h)throw new m("BAD_REQUEST",{message:b.SESSION_EXPIRED})}if(e.body.token)return await ii({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if((o=e.context.options.user.deleteUser)!=null&&o.sendDeleteAccountVerification){const u=Xe(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${u}`,expiresAt:new Date(Date.now()+(((d=e.context.options.user.deleteUser)==null?void 0:d.deleteTokenExpiresIn)||60*60*24)*1e3)});const h=`${e.context.baseURL}/delete-user/callback?token=${u}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:h,token:u},e.request),e.json({success:!0,message:"Verification email sent"})}const r=(c=e.context.options.user.deleteUser)==null?void 0:c.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),pe(e);const n=(l=e.context.options.user.deleteUser)==null?void 0:l.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})});const ii=U("/delete-user/callback",{method:"GET",query:f.object({token:f.string(),callbackURL:f.string().optional()}),use:[dt(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=>{var i,a,o,d;if(!((a=(i=e.context.options.user)==null?void 0:i.deleteUser)!=null&&a.enabled))throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new m("NOT_FOUND");const t=await ce(e);if(!t)throw new m("NOT_FOUND",{message:b.FAILED_TO_GET_USER_INFO});const r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw new m("NOT_FOUND",{message:b.INVALID_TOKEN});if(r.value!==t.user.id)throw new m("NOT_FOUND",{message:b.INVALID_TOKEN});const n=(o=e.context.options.user.deleteUser)==null?void 0:o.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),pe(e);const s=(d=e.context.options.user.deleteUser)==null?void 0:d.afterDelete;if(s&&await s(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})});U("/change-email",{method:"POST",body:f.object({newEmail:f.string({description:"The new email to set"}).email(),callbackURL:f.string({description:"The URL to redirect to after email verification"}).optional()}),use:[Q],metadata:{openapi:{responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{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=>{var i,a,o,d,c;if(!((a=(i=e.context.options.user)==null?void 0:i.changeEmail)!=null&&a.enabled))throw e.context.logger.error("Change email is disabled."),new m("BAD_REQUEST",{message:"Change email is disabled"});const t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new m("BAD_REQUEST",{message:"Email is the same"});
4if(await e.context.internalAdapter.findUserByEmail(t))throw e.context.logger.error("Email already exists"),new m("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){if(await e.context.internalAdapter.findUserByEmail(t))throw new m("UNPROCESSABLE_ENTITY",{message:b.USER_ALREADY_EXISTS});if(await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:t},e),await Z(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),(o=e.context.options.emailVerification)!=null&&o.sendVerificationEmail){const u=await me(e.context.secret,t,void 0,(d=e.context.options.emailVerification)==null?void 0:d.expiresIn),h=`${e.context.baseURL}/verify-email?token=${u}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:{...e.context.session.user,email:t},url:h,token:u},e.request)}return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new m("BAD_REQUEST",{message:"Verification email isn't enabled"});const n=await me(e.context.secret,e.context.session.user.email,t,(c=e.context.options.emailVerification)==null?void 0:c.expiresIn),s=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:t,url:s,token:n},e.request),e.json({status:!0})});function ai(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const oi=(e="Unknown")=>`<!DOCTYPE html> 5<html lang="en"> 6<head> 7 <meta charset="UTF-8"> 8 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 9 <title>Authentication Error</title> 10 <style> 11 :root { 12 --bg-color: #f8f9fa; 13 --text-color: #212529; 14 --accent-color: #000000; 15 --error-color: #dc3545; 16 --border-color: #e9ecef; 17 } 18 body { 19 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 20 background-color: var(--bg-color); 21 color: var(--text-color); 22 display: flex; 23 justify-content: center; 24 align-items: center; 25 height: 100vh; 26 margin: 0; 27 line-height: 1.5; 28 } 29 .error-container { 30 background-color: #ffffff; 31 border-radius: 12px; 32 box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05); 33 padding: 2.5rem; 34 text-align: center; 35 max-width: 90%; 36 width: 400px; 37 } 38 h1 { 39 color: var(--error-color); 40 font-size: 1.75rem; 41 margin-bottom: 1rem; 42 font-weight: 600; 43 } 44 p { 45 margin-bottom: 1.5rem; 46 color: #495057; 47 } 48 .btn { 49 background-color: var(--accent-color); 50 color: #ffffff; 51 text-decoration: none; 52 padding: 0.75rem 1.5rem; 53 border-radius: 6px; 54 transition: all 0.3s ease; 55 display: inline-block; 56 font-weight: 500; 57 border: 2px solid var(--accent-color); 58 } 59 .btn:hover { 60 background-color: #131721; 61 } 62 .error-code { 63 font-size: 0.875rem; 64 color: #6c757d; 65 margin-top: 1.5rem; 66 padding-top: 1.5rem; 67 border-top: 1px solid var(--border-color); 68 } 69 .icon { 70 font-size: 3rem; 71 margin-bottom: 1rem; 72 } 73 </style> 74</head> 75<body> 76 <div class="error-container"> 77 <div class="icon">â ï¸</div> 78 <h1>Better Auth Error</h1> 79 <p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p> 80 <a href="/" id="returnLink" class="btn">Return to Application</a> 81 <div class="error-code">Error Code: <span id="errorCode">${ai(e)}</span></div> 82 </div> 83</body> 84</html>`;U("/error",{method:"GET",metadata:{...lt,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=>{var r;const t=new URL(((r=e.request)==null?void 0:r.url)||"").searchParams.get("error")||"Unknown";return new Response(oi(t),{headers:{"Content-Type":"text/html"}})});U("/ok",{method:"GET",metadata:{...lt,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}));U("/list-accounts",{method:"GET",use:[Q],metadata:{openapi:{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"},provider:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},accountId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","provider","createdAt","updatedAt","accountId","scopes"]}}}}}}}},async e=>
84{const t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(n=>{var s;return{id:n.id,provider:n.providerId,createdAt:n.createdAt,updatedAt:n.updatedAt,accountId:n.accountId,scopes:((s=n.scope)==null?void 0:s.split(","))||[]}}))});U("/link-social",{method:"POST",requireHeaders:!0,body:f.object({callbackURL:f.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:f.enum(Sr,{description:"The OAuth2 provider to use"}),scopes:f.array(f.string(),{description:"Additional scopes to request from the provider"}).optional()}),use:[Q],metadata:{openapi:{description:"Link a social account to the user",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"}},required:["url","redirect"]}}}}}}}},async e=>{const t=e.context.session,r=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new m("NOT_FOUND",{message:b.PROVIDER_NOT_FOUND});const n=await Tr(e,{userId:t.user.id,email:t.user.email}),s=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`,scopes:e.body.scopes});return e.json({url:s.toString(),redirect:!0})});U("/unlink-account",{method:"POST",body:f.object({providerId:f.string(),accountId:f.string().optional()}),use:[ni],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{var i,a;const{providerId:t,accountId:r}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(n.length===1&&!((a=(i=e.context.options.account)==null?void 0:i.accountLinking)!=null&&a.allowUnlinkingAll))throw new m("BAD_REQUEST",{message:b.FAILED_TO_UNLINK_LAST_ACCOUNT});const s=n.find(o=>r?o.accountId===r&&o.providerId===t:o.providerId===t);if(!s)throw new m("BAD_REQUEST",{message:b.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(s.id),e.json({status:!0})});U("/refresh-token",{method:"POST",body:f.object({providerId:f.string({description:"The provider ID for the OAuth provider"}),accountId:f.string({description:"The account ID associated with the refresh token"}).optional(),userId:f.string({description:"The user ID associated with the account"}).optional()}),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=>{var l;const{providerId:t,accountId:r,userId:n}=e.body,s=e.request,i=await ce(e);if(s&&!i)throw e.error("UNAUTHORIZED");let a=((l=i==null?void 0:i.user)==null?void 0:l.id)||n;if(!a)throw new m("BAD_REQUEST",{message:"Either userId or session is required"});const d=(await e.context.internalAdapter.findAccounts(a)).find(u=>r?u.id===r&&u.providerId===t:u.providerId===t);if(!d)throw new m("BAD_REQUEST",{message:"Account not found"});const c=e.context.socialProviders.find(u=>u.id===t);if(!c)throw new m("BAD_REQUEST",{message:`Provider ${t} not found.`});if(!c.refreshAccessToken)throw new m("BAD_REQUEST",{message:`Provider ${t} does not support token refreshing.`});try{const u=await c.refreshAccessToken(d.refreshToken);return await e.context.internalAdapter.updateAccount(d.id,{accessToken:u.accessToken,accessTokenExpiresAt:u.accessTokenExpiresAt,refreshToken:u.refreshToken,refreshTokenExpiresAt:u.refreshTokenExpiresAt}),e.json(u)}
84catch(u){throw new m("BAD_REQUEST",{message:"Failed to refresh access token",cause:u})}});const ci={user:{fields:{username:{type:"string",required:!1,sortable:!0,unique:!0,returned:!0,transform:{input(e){return e==null?void 0:e.toString().toLowerCase()}}},displayUsername:{type:"string",required:!1}}}},C={INVALID_USERNAME_OR_PASSWORD:"invalid username or password",EMAIL_NOT_VERIFIED:"email not verified",UNEXPECTED_ERROR:"unexpected error",USERNAME_IS_ALREADY_TAKEN:"username is already taken. please try another.",USERNAME_TOO_SHORT:"username is too short",USERNAME_TOO_LONG:"username is too long",INVALID_USERNAME:"username is invalid"};function Ot(e){return/^[a-zA-Z0-9_.]+$/.test(e)}const rt=e=>({id:"username",endpoints:{signInUsername:U("/sign-in/username",{method:"POST",body:f.object({username:f.string({description:"The username of the user"}),password:f.string({description:"The password of the user"}),rememberMe:f.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"Session token for the authenticated session"},user:{$ref:"#/components/schemas/User"}},required:["token","user"]}}}}}}}},async t=>{var l;if(!t.body.username||!t.body.password)throw t.context.logger.error("Username or password not found"),new m("UNAUTHORIZED",{message:C.INVALID_USERNAME_OR_PASSWORD});const r=(e==null?void 0:e.minUsernameLength)||3,n=(e==null?void 0:e.maxUsernameLength)||30;if(t.body.username.length<r)throw t.context.logger.error("Username too short",{username:t.body.username}),new m("UNPROCESSABLE_ENTITY",{message:C.USERNAME_TOO_SHORT});if(t.body.username.length>n)throw t.context.logger.error("Username too long",{username:t.body.username}),new m("UNPROCESSABLE_ENTITY",{message:C.USERNAME_TOO_LONG});if(!((e==null?void 0:e.usernameValidator)||Ot)(t.body.username))throw new m("UNPROCESSABLE_ENTITY",{message:C.INVALID_USERNAME});const i=await t.context.adapter.findOne({model:"user",where:[{field:"username",value:t.body.username.toLowerCase()}]});if(!i)throw await t.context.password.hash(t.body.password),t.context.logger.error("User not found",{username:rt}),new m("UNAUTHORIZED",{message:C.INVALID_USERNAME_OR_PASSWORD});if(!i.emailVerified&&((l=t.context.options.emailAndPassword)!=null&&l.requireEmailVerification))throw await Ir(t,i),new m("FORBIDDEN",{message:C.EMAIL_NOT_VERIFIED});const a=await t.context.adapter.findOne({model:"account",where:[{field:"userId",value:i.id},{field:"providerId",value:"credential"}]});if(!a)throw new m("UNAUTHORIZED",{message:C.INVALID_USERNAME_OR_PASSWORD});const o=a==null?void 0:a.password;if(!o)throw t.context.logger.error("Password not found",{username:rt}),new m("UNAUTHORIZED",{message:C.INVALID_USERNAME_OR_PASSWORD});if(!await t.context.password.verify({hash:o,password:t.body.password}))throw t.context.logger.error("Invalid password"),new m("UNAUTHORIZED",{message:C.INVALID_USERNAME_OR_PASSWORD});const c=await t.context.internalAdapter.createSession(i.id,t.headers,t.body.rememberMe===!1);return c?(await Z(t,{session:c,user:i},t.body.rememberMe===!1),t.json({token:c.token,user:{id:i.id,email:i.email,emailVerified:i.emailVerified,username:i.username,name:i.name,image:i.image,createdAt:i.createdAt,updatedAt:i.updatedAt}})):t.json(null,{status:500,body:{message:b.FAILED_TO_CREATE_SESSION}})})},schema:Gs(ci,e==null?void 0:e.schema),hooks:{before:[{matcher(t){return t.path==="/sign-up/email"||t.path==="/update-user"},handler:oe(async t=>{const r=t.body.username;if(r!==void 0&&typeof r=="string"){const n=(e==null?void 0:e.minUsernameLength)||3,s=(e==null?void 0:e.maxUsernameLength)||30;if(r.length<n)throw new m("UNPROCESSABLE_ENTITY",{message:C.USERNAME_TOO_SHORT});if(r.length>s)throw new m("UNPROCESSABLE_ENTITY",{message:C.USERNAME_TOO_LONG});if(!await((e==null?void 0:e.usernameValidator)||Ot)(r))throw new m("UNPROCESSABLE_ENTITY",{message:C.INVALID_USERNAME});if(await t.context.adapter.findOne({model:"user",where:[{field:"username",value:r.toLowerCase()}]}
84))throw new m("UNPROCESSABLE_ENTITY",{message:C.USERNAME_IS_ALREADY_TAKEN})}})},{matcher(t){return t.path==="/sign-up/email"||t.path==="/update-user"},handler:oe(async t=>{!t.body.displayUsername&&t.body.username&&(t.body.displayUsername=t.body.username)})}]},$ERROR_CODES:C}),di={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*:/},li=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Dt={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},ui=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function fi(e){return e instanceof Date&&!isNaN(e.getTime())}function hi(e){const t=ui.exec(e);if(!t)return null;const[,r,n,s,i,a,o,d,c,l,u]=t;let h=new Date(Date.UTC(parseInt(r,10),parseInt(n,10)-1,parseInt(s,10),parseInt(i,10),parseInt(a,10),parseInt(o,10),d?parseInt(d.padEnd(3,"0"),10):0));if(c){const p=(parseInt(l,10)*60+parseInt(u,10))*(c==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+p)}return fi(h)?h:null}function pi(e,t={}){const{strict:r=!1,warnings:n=!1,reviver:s,parseDates:i=!0}=t;if(typeof e!="string")return e;const a=e.trim();if(a[0]==='"'&&a.endsWith('"')&&!a.slice(1,-1).includes('"'))return a.slice(1,-1);const o=a.toLowerCase();if(o.length<=9&&o in Dt)return Dt[o];if(!li.test(a)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(di).some(([c,l])=>{const u=l.test(a);return u&&n&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${c} pattern`),u})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(a,(l,u)=>{if(l==="__proto__"||l==="constructor"&&u&&typeof u=="object"&&"prototype"in u){n&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(i&&typeof u=="string"){const h=hi(u);if(h)return h}return s?s(l,u):u})}catch(c){if(r)throw c;return e}}function mi(e,t={strict:!0}){return pi(e,t)}const gi={id:"redirect",name:"Redirect",hooks:{onSuccess(e){var t,r;if((t=e.data)!=null&&t.url&&((r=e.data)!=null&&r.redirect)&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function wi(e){const t=Nt(!1);return{session:un(t,"/get-session",e,{method:"GET"}),$sessionSignal:t}}const yi=e=>{var p,w,A,y,_;const t="credentials"in Request.prototype,r=An(e==null?void 0:e.baseURL,e==null?void 0:e.basePath),n=((p=e==null?void 0:e.plugins)==null?void 0:p.flatMap(g=>g.fetchPlugins).filter(g=>g!==void 0))||[],s=sn({baseURL:r,...t?{credentials:"include"}:{},method:"GET",jsonParser(g){return g?mi(g,{strict:!1}):null},customFetchImpl:async(g,T)=>{try{return await fetch(g,T)}catch{return Response.error()}},...e==null?void 0:e.fetchOptions,plugins:e!=null&&e.disableDefaultFetchPlugins?[...((w=e==null?void 0:e.fetchOptions)==null?void 0:w.plugins)||[],...n]:[gi,...((A=e==null?void 0:e.fetchOptions)==null?void 0:A.plugins)||[],...n]}),{$sessionSignal:i,session:a}=wi(s),o=(e==null?void 0:e.plugins)||[];let d={},c={$sessionSignal:i,session:a},l={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"};const u=[{signal:"$sessionSignal",matcher(g){return g==="/sign-out"||g==="/update-user"||g.startsWith("/sign-in")||g.startsWith("/sign-up")||g==="/delete-user"||g==="/verify-email"}}];for(const g of o)g.getAtoms&&Object.assign(c,(y=g.getAtoms)==null?void 0:y.call(g,s)),g.pathMethods&&Object.assign(l,g.pathMethods),g.atomListeners&&u.push(...g.atomListeners);const h={notify:g=>{c[g].set(!c[g].get())},listen:(g,T)=>{c[g].subscribe(T)},atoms:c};for(const g of o)g.getActions&&Object.assign(d,(_=g.getActions)==null?void 0:_.call(g,s,h));return{pluginsActions:d,pluginsAtoms:c,pluginPathMethods:l,atomListeners:u,$fetch:s,$store:h}};function Ei(e,t,r){const n=t[e],{fetchOptions:s,query:i,...a}=r||{};return n||(s!=null&&s.method?s.method:a&&Object.keys(a).length>0?"POST":"GET")}function bi(e,t,r,n,s){function i(a=[]){return new Proxy(function(){},{get(o,d){const c=[...a,d];let l=e;for(const u of c)if(l&&typeof l=="object"&&u in l)l=l[u];else{l=void 0;break}return typeof l=="function"?l:i(c)},apply:async(o,d,c)=>{const l="/"+a.map(g=>g.replace(/[A-Z]/g,T=>`-${T.toLowerCase()}`)).join("/"),u=c[0]||{},h=c[1]||{},{query:p,fetchOptions:w,...A}=u,y={...h,...w},_=Ei(l,r,u);return await t(l,{...y,body:_==="GET"?void 0:{...A,...(y==null?void 0:y.body)||{}},query:p||(y==null?void 0:y.query),method:_,async onSuccess(g){var S;await((S=y==null?void 0:y.onSuccess)==null?void 0:S.call(y,g));const T=s==null?void 0:s.find(G=>G.matcher(l));if(!T)return;const E=n[T.signal];if(!E)return;const k=E.get();setTimeout(()=>{E.set(!k)},10)}})}})}return i()}function Ai(e,t={}){let r=We.useRef(e.get());const{keys:n,deps:s=[e,n]}=t;let i=We.useCallback(o=>{const d=c=>{r.current!==c&&(r.current=c,o())};return d(e.value),n!=null&&n.length?$r(e,n,d):e.listen(d)},s),a=()=>r.current;return We.useSyncExternalStore(i,a,a)}function _i(e){return`use${Si(e)}`}function Si(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ti(e){const{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:n,$fetch:s,$store:i,atomListeners:a}=yi(e);let o={};for(const[l,u]of Object.entries(n))o[_i(l)]=()=>Ai(u);const d={...r,...o,$fetch:s,$store:i};return bi(d,s,t,n,a)}const Ri=Ti({baseURL:Dr.VITE_APP_URL,plugins:[wn(),rt()]}
84),{signOut:Oi,signIn:Di,signUp:Li,useSession:Ni}=Ri;export{Li as a,Ri as b,Oi as c,Di as s,Ni as u};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.