1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,551956,e=>{"use strict";var t=e.i(90985),r=e.i(804730);let o={app_url:"https://www.whydidiraiseahuman.top",app_name:"whydidiraiseahuman",app_description:t.default.env.NEXT_PUBLIC_APP_DESCRIPTION??"The complete fan guide to GENJOYBOY's dark fantasy series on Trimz: what it is, where to watch, episode count, and story guides.",app_logo:t.default.env.NEXT_PUBLIC_APP_LOGO??"/logo.svg",app_favicon:t.default.env.NEXT_PUBLIC_APP_FAVICON??"/favicon.svg",app_preview_image:t.default.env.NEXT_PUBLIC_APP_PREVIEW_IMAGE??"/preview.png",theme:"default",appearance:"system",locale:t.default.env.NEXT_PUBLIC_DEFAULT_LOCALE??"en",database_url:t.default.env.DATABASE_URL??"",database_auth_token:t.default.env.DATABASE_AUTH_TOKEN??"",database_provider:t.default.env.DATABASE_PROVIDER??"postgresql",db_schema_file:t.default.env.DB_SCHEMA_FILE??"./src/config/db/schema.ts",db_schema:t.default.env.DB_SCHEMA??"public",db_migrations_table:t.default.env.DB_MIGRATIONS_TABLE??"__drizzle_migrations",db_migrations_schema:t.default.env.DB_MIGRATIONS_SCHEMA??"drizzle",db_migrations_out:t.default.env.DB_MIGRATIONS_OUT??"./src/config/db/migrations",db_singleton_enabled:t.default.env.DB_SINGLETON_ENABLED||"false",db_max_connections:t.default.env.DB_MAX_CONNECTIONS||"1",auth_url:t.default.env.AUTH_URL||"https://www.whydidiraiseahuman.top",auth_secret:t.default.env.AUTH_SECRET??"",google_site_verification:t.default.env.GOOGLE_SITE_VERIFICATION??"",bing_site_verification:t.default.env.BING_SITE_VERIFICATION??"",version:r.default.version,locale_detect_enabled:t.default.env.NEXT_PUBLIC_LOCALE_DETECT_ENABLED??"false"};e.s(["envConfigs",0,o])},400969,e=>{"use strict";let t,r,o,n,i,s;var a,c,d=e.i(90985);let l=[],u=0,p=0,f=e=>{let t=[],r={get:()=>(r.lc||r.listen(()=>{})(),r.value),lc:0,listen:e=>(r.lc=t.push(e),()=>{for(let t=u+4;t<l.length;)l[t]===e?l.splice(t,4):t+=4;let o=t.indexOf(e);~o&&(t.splice(o,1),--r.lc||r.off())}),notify(e,o){p++;let n=!l.length;for(let n of t)l.push(n,r.value,e,o);if(n){for(u=0;u<l.length;u+=4)l[u](l[u+1],l[u+2],l[u+3]);l.length=0}},off(){},set(e){let t=r.value;t!==e&&(r.value=e,r.notify(t))},subscribe(e){let t=r.listen(e);return e(r.value),t},value:e};return r};var h=Object.defineProperty,m=Object.defineProperties,y=Object.getOwnPropertyDescriptors,g=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,b=Object.prototype.propertyIsEnumerable,v=(e,t,r)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,E=(e,t)=>{for(var r in t||(t={}))w.call(t,r)&&v(e,r,t[r]);if(g)for(var r of g(t))b.call(t,r)&&v(e,r,t[r]);return e},A=(e,t)=>
1m(e,y(t)),x=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},T=async(e,t)=>{var r,o,n,i,s,a;let c=t||{},d={onRequest:[null==t?void 0:t.onRequest],onResponse:[null==t?void 0:t.onResponse],onSuccess:[null==t?void 0:t.onSuccess],onError:[null==t?void 0:t.onError],onRetry:[null==t?void 0:t.onRetry]};if(!t||!(null==t?void 0:t.plugins))return{url:e,options:c,hooks:d};for(let l of(null==t?void 0:t.plugins)||[]){if(l.init){let o=await (null==(r=l.init)?void 0:r.call(l,e.toString(),t));c=o.options||c,e=o.url}d.onRequest.push(null==(o=l.hooks)?void 0:o.onRequest),d.onResponse.push(null==(n=l.hooks)?void 0:n.onResponse),d.onSuccess.push(null==(i=l.hooks)?void 0:i.onSuccess),d.onError.push(null==(s=l.hooks)?void 0:s.onError),d.onRetry.push(null==(a=l.hooks)?void 0:a.onRetry)}return{url:e,options:c,hooks:d}},k=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}},S=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)}},_=async e=>{let t={},r=async e=>"function"==typeof e?await e():e;if(null==e?void 0:e.auth){if("Bearer"===e.auth.type){let o=await r(e.auth.token);if(!o)return t;t.authorization=`Bearer ${o}`}else if("Basic"===e.auth.type){let o=r(e.auth.username),n=r(e.auth.password);if(!o||!n)return t;t.authorization=`Basic ${btoa(`${o}:${n}`)}`}else if("Custom"===e.auth.type){let o=r(e.auth.value);if(!o)return t;t.authorization=`${r(e.auth.prefix)} ${o}`}}return t},R=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function U(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}function I(e){try{return JSON.parse(e)}catch(t){return e}}function O(e){return"function"==typeof e}async function P(e){let t=new Headers(null==e?void 0:e.headers);for(let[r,o]of Object.entries(await _(e)||{}))t.set(r,o);if(!t.has("content-type")){let r=U(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var D=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function L(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new D(r.issues);return r.value}var Z=["get","post","put","patch","delete"],j=async(e,t)=>{var r,o,n,i,s,a,c,d;let l,{hooks:u,url:p,options:f}=await T(e,t),h=function(e){if(null==e?void 0:e.customFetchImpl)return e.customFetchImpl;if("undefined"!=typeof globalThis&&O(globalThis.fetch))return globalThis.fetch;if("undefined"!=typeof window&&O(window.fetch))return window.fetch;throw Error("No fetch implementation found")}(f),m=new AbortController,y=null!=(r=f.signal)?r:m.signal,g=function(e,t){let{baseURL:r,params:o,query:n}=t||{query:{},params:{},baseURL:""},i=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let t=e.toString().split("@")[1].split("/")[0];Z.includes(t)&&(e=e.replace(`@${t}/`,"/"))}i.endsWith("/")||(i+="/");let[s,a]=e.replace(i,"").split("?"),c=new URLSearchParams(a);for(let[e,t]of Object.entries(n||{}))null!=t&&c.set(e,String(t));if(o)if(Array.isArray(o))for(let[e,t]of s.split("/").filter(e=>e.startsWith(":")).entries()){let r=o[e];s=s.replace(t,r)}else for(let[e,t]of Object.entries(o))s=s.replace(`:${e}`,String(t));(s=s.split("/").map(encodeURIComponent).join("/")).startsWith("/")&&(s=s.slice(1));let d=c.toString();return(d=d.length>0?`?${d}`.replace(/\+/g,"%20"):"",i.startsWith("http"))?new URL(`${s}${d}`,i):`${i}${s}${d}`}(p,f),w=function(e){if(!(null==e?void 0:e.body))return null;let t=new Headers(null==e?void 0:e.headers);if(U(e.body)&&!t.has("content-type")){for(let[t,r]of Object.entries(null==e?void 0:e.body))r instanceof Date&&(e.body[t]=r.toISOString());return JSON.stringify(e.body)}return e.body}(f),b=await P(f),v=function(e,t){var r;if(null==t?void 0:t.method)return t.method.toUpperCase();if(e.startsWith("@")){let o=null==(r=e.split("@")[1])?void 0:r.split("/")[0];return Z.includes(o)?o.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}return(null==t?void 0:t.body)?"POST":"GET"}(p,f),_=A(E({},f),{url:g,headers:b,body:w,method:v,signal:y});for(let e of u.onRequest)if(e){let t=await e(_);t instanceof Object&&(_=t)}("pipeTo"in _&&"function"==typeof _.pipeTo||"function"==typeof(null==(o=null==t?void 0:t.body)?void 0:o.pipe))&&!("duplex"in _)&&(_.duplex="half");let{clearTimeout:D}=(!(null==f?void 0:f.signal)&&(null==f?void 0:f.timeout)&&(l=setTimeout(()=>null==m?void 0:m.abort(),null==f?void 0:f.timeout)),{abortTimeout:l,clearTimeout:()=>{l&&clearTimeout(l)}}),C=await h(_.url,_);D();let N={response:C,request:_};for(let e of u.onResponse)if(e){let r=await e(A(E({},N),{response:(null==(n=null==t?void 0:t.hookOptions)?void 0:n.cloneResponse)?C.clone():C}));r instanceof Response?C=r:r instanceof Object&&(C=r.response)}if(C.ok){if("HEAD"===_.method)return{data:"",error:null};let e=function(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let o=t.split(";").shift()||"";return R.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}(C),r={data:"",response:C,request:_};if("json"===e||"text"===e){let e=await C.text(),t=null!=(i=_.jsonParser)?i:I;r.data=await t(e)}else r.data=await C[e]();for(let e of((null==_?void 0:_.output)&&_.output&&!_.disableValidation&&(r.data=await L(_.output,r.data)),u.onSuccess))e&&await e(A(E({},r),{response:(null==(s=null==t?void 0:t.hookOptions)?void 0:s.cloneResponse)?C.clone():C}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let $=null!=(a=null==t?void 0:t.jsonParser)?a:I,z=await C.text(),H=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(z),V=H?await $(z):null,q={response:C,responseText:z,request:_,error:A(E({},V),{status:C.status,statusText:C.statusText})};for(let e of u.onError)e&&await e(A(E({},q),{response:(null==(c=null==t?void 0:t.hookOptions)?void 0:c.cloneResponse)?C.clone():C}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new k({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new k(e);case"exponential":return new S(e);default:throw Error("Invalid retry strategy")}}(t.retry),o=null!=(d=t.retryAttempt)?d:0;if(await r.shouldAttemptRetry(o,C)){for(let e of u.onRetry)e&&await e(N);let n=r.getDelay(o);return await new Promise(e=>setTimeout(e,n)),await j(e,A(E({},t),{retryAttempt:o+1}))}}if(null==t?void 0:t.throw)throw new x(C.status,C.statusText,H?V:z);return{data:null,error:A(E({},V),{status:C.status,statusText:C.statusText})}};let C=Object.create(null),N=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?C:globalThis),$=new Proxy(C,{get:(e,t)=>N()[t]??C[t],has:(e,t)=>t in N()||t in C,set:(e,t,r)=>(N(!0)[t]=r,!0),deleteProperty(e,t){if(!t)return!1;let r=N(!0);return delete r[t],!0},ownKeys:()=>Object.keys(N(!0))}),z=void 0!==d.default&&d.default.env&&"production"||"",H="dev"===z||"development"===z,V=(e,t)=>{var r,o;return r=r=>{let o=t(r);o&&e.events[6].push(o)},o=t=>{let r=e.listen;e.listen=(...o)=>(e.lc||e.active||(e.active=!0,t()),r(...o));let o=e.off;return e.events[6]=[],e.off=()=>{o(),setTimeout(()=>
1{if(e.active&&!e.lc){for(let t of(e.active=!1,e.events[6]))t();e.events[6]=[]}},1e3)},()=>{e.listen=r,e.off=o}},e.events=e.events||{},e.events[15]||(e.events[15]=o(t=>{e.events[5].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[5]=e.events[5]||[],e.events[5].push(r),()=>{let t=e.events[5],o=t.indexOf(r);t.splice(o,1),t.length||(delete e.events[5],e.events[15](),delete e.events[15])}},q="undefined"==typeof window;class B extends Error{constructor(e,t){super(e),this.name="BetterAuthError",this.message=e,this.cause=t,this.stack=""}}function K(e){return{newRole:e=>{var t;return{authorize(e,r="AND"){let o=!1;for(let[n,i]of Object.entries(e)){let e=t[n];if(!e)return{success:!1,error:`You are not allowed to access resource: ${n}`};if(Array.isArray(i))o=i.every(t=>e.includes(t));else if("object"==typeof i)o="OR"===i.connector?i.actions.some(t=>e.includes(t)):i.actions.every(t=>e.includes(t));else throw new B("Invalid access control request");if(o&&"OR"===r)return{success:o};if(!o&&"AND"===r)return{success:!1,error:`unauthorized to access resource "${n}"`}}return o?{success:o}:{success:!1,error:"Not authorized"}},statements:t=e}},statements:e}}let M=K({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]});M.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),M.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),M.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});var W=e.i(598439);let F=globalThis.crypto,J=F.subtle,G=e=>F.getRandomValues(e);var Q=Object.defineProperty,Y={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},X=function(e,t){class r extends e{#e;constructor(...e){if(function(){let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return void 0===e?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,"writable")?e.writable:void 0!==e.set}()){const t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);const t=Error().stack;t&&(this.#e=function(e){let t=e.split("\n at ");return t.length<=1?e:(t.splice(1,1),t.join("\n at "))}(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get:()=>t,enumerable:!1,configurable:!0}),r}(class extends Error{constructor(e="INTERNAL_SERVER_ERROR",t,r={},o="number"==typeof e?e:Y[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=r,this.statusCode=o,this.name="APIError",this.status=e,this.headers=r,this.statusCode=o,this.body=t?{code:t?.message?.toUpperCase().replace(/ /g,"_").replace(/[^A-Z0-9_]/g,""),...t}:void 0}},Error);function ee(e){return e instanceof X||e?.name==="APIError"}async function et(e,t={}){let r={body:t.body,query:t.query};if(e.body){let o=await e.body["~standard"].validate(t.body);if(o.issues)return{data:null,error:er(o.issues,"body")};r.body=o.value}if(e.query){let o=await e.query["~standard"].validate(t.query);if(o.issues)return{data:null,error:er(o.issues,"query")};r.query=o.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 er(e,t){let r=[];for(let t of e){let e=t.message;r.push(e)}return{message:`Invalid ${t} parameters`}}var eo={name:"HMAC",hash:"SHA-256"},en=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await J.importKey("raw",t,eo,!1,["sign","verify"])},ei=async(e,t,r)=>{try{let o=atob(e),n=new Uint8Array(o.length);for(let e=0,t=o.length;e<t;
1e++)n[e]=o.charCodeAt(e);return await J.verify(eo,r,n,new TextEncoder().encode(t))}catch(e){return!1}},es=async(e,t)=>{let r=await en(t);return btoa(String.fromCharCode(...new Uint8Array(await J.sign(eo.name,r,new TextEncoder().encode(e)))))},ea=async(e,t)=>{let r=await es(e,t);return encodeURIComponent(e=`${e}.${r}`)},ec=(e,t)=>{let r=e;if(t)if("secure"===t)r="__Secure-"+e;else{if("host"!==t)return;r="__Host-"+e}return r},ed=(e,t,r={})=>{let o;if(o=r?.prefix==="secure"?`__Secure-${e}=${t}`:r?.prefix==="host"?`__Host-${e}=${t}`:`${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&&"number"==typeof r.maxAge&&r.maxAge>=0){if(r.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");o+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&"host"!==r.prefix&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");o+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(o+="; HttpOnly"),r.secure&&(o+="; Secure"),r.sameSite&&(o+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),o+="; Partitioned"),o},el=async(e,t,r,o)=>ed(e,t=await ea(t,r),o),eu=async(e,{options:t,path:r})=>{let o=new Headers,{data:n,error:i}=await et(t,e);if(i)throw new X(400,{message:i.message,code:"VALIDATION_ERROR"});let s="headers"in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&e.request instanceof Request?e.request.headers:null,a=s?.get("cookie"),c=a?function(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let o=e.indexOf("=",r);
1if(-1===o)break;let n=e.indexOf(";",r);if(-1===n)n=e.length;else if(n<o){r=e.lastIndexOf(";",o-1)+1;continue}let i=e.slice(r,o).trim();if(!t.has(i)){let r=e.slice(o+1,n).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(i,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=n+1}return t}(a):void 0,d={...e,body:n.body,query:n.query,path:e.path||r,context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:"params"in e?e.params:void 0,method:e.method,setHeader:(e,t)=>{o.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let r=ec(e,t);return r&&c?.get(r)||null},getSignedCookie:async(e,t,r)=>{let o=ec(e,r);if(!o)return null;let n=c?.get(o);if(!n)return null;let i=n.lastIndexOf(".");if(i<1)return null;let s=n.substring(0,i),a=n.substring(i+1);if(44!==a.length||!a.endsWith("="))return null;let d=await en(t);return!!await ei(a,s,d)&&s},setCookie:(e,t,r)=>{var n;let i=ed(e,n=encodeURIComponent(n=t),r);return o.append("set-cookie",i),i},setSignedCookie:async(e,t,r,n)=>{let i=await el(e,t,r,n);return o.append("set-cookie",i),i},redirect:e=>(o.set("location",e),new X("FOUND",void 0,o)),error:(e,t,r)=>new X(e,t,r),json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:o};for(let e of t.use||[]){let t=await e({...d,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(d.context,t.response),t.headers&&t.headers.forEach((e,t)=>{d.responseHeaders.set(t,e)})}return d};function ep(e,t){let r=async r=>{let o="function"==typeof e?e:t,n=await eu(r,{options:"function"==typeof e?{}:e,path:"/"});if(!o)throw Error("handler must be defined");let i=await o(n),s=n.responseHeaders;return r.returnHeaders?{headers:s,response:i}:i};return r.options="function"==typeof e?{}:e,r}ep.create=e=>function(t,r){if("function"==typeof t)return ep({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return ep({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)};var ef=(e,t,r)=>{let o=async(...o)=>{let n=o[0]||{},i=await eu(n,{options:t,path:e}),s=await r(i).catch(async e=>{if(ee(e)){let r=t.onAPIError;if(r&&await r(e),n.asResponse)return e}throw e}),a=i.responseHeaders;return n.asResponse?function e(t,r){if(t instanceof Response)return r?.headers instanceof Headers&&r.headers.forEach((e,r)=>{t.headers.set(r,e)}),t;if(t&&"object"==typeof t&&"_flag"in t&&"json"===t._flag){let e=t.body,o=t.routerResponse;if(o instanceof Response)return o;let n=new Headers({...o?.headers,...t.headers,...r?.headers,"Content-Type":"application/json"});return new Response(JSON.stringify(e),{...o,headers:n,status:t.status??r?.status??o?.status,statusText:r?.statusText??o?.statusText})}if(ee(t))return e(t.body,{status:r?.status??t.statusCode,statusText:t.status.toString(),headers:r?.headers||t.headers});let o=t,n=new Headers(r?.headers);if(t){if("string"==typeof t)o=t,n.set("Content-Type","text/plain");else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))o=t,n.set("Content-Type","application/octet-stream");else if(t instanceof Blob)o=t,n.set("Content-Type",t.type||"application/octet-stream");else if(t instanceof FormData)o=t;else if(t instanceof URLSearchParams)o=t,n.set("Content-Type","application/x-www-form-urlencoded");else if(t instanceof ReadableStream)o=t,n.set("Content-Type","application/octet-stream");else if(function(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}(t)){let e,r;e=0,r=new WeakMap,o=JSON.stringify(t,(t,o)=>{if("bigint"==typeof o)return o.toString();if("object"==typeof o&&null!==o){if(r.has(o))return`[Circular ref-${r.get(o)}]`;r.set(o,e++)}return o},void 0),n.set("Content-Type","application/json")}}else null===t&&(o=JSON.stringify(null)),n.set("content-type","application/json");return new Response(o,{...r,headers:n})}(s,{headers:a}):n.returnHeaders?{headers:a,response:s}:s};return o.options=t,o.path=e,o};function eh(e,t,r){function o(r,o){var n;for(let i in Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,o),s.prototype)i in r||Object.defineProperty(r,i,{value:s.prototype[i].bind(r)});r._zod.constr=s,r._zod.def=o}
1let n=r?.Parent??Object;class i extends n{}function s(e){var t;let n=r?.Parent?new i:this;for(let r of(o(n,e),(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred))r();return n}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}ef.create=e=>(t,r,o)=>ef(t,{...r,use:[...r?.use||[],...e?.use||[]]},o),Object.freeze({status:"aborted"}),Symbol("zod_brand");var em=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ey={};function eg(e){return e&&Object.assign(ey,e),ey}var ew={},eb={BIGINT_FORMAT_RANGES:()=>e0,Class:()=>ti,NUMBER_FORMAT_RANGES:()=>eX,aborted:()=>e3,allowsEval:()=>eH,assert:()=>ek,assertEqual:()=>eE,assertIs:()=>ex,assertNever:()=>eT,assertNotEqual:()=>eA,assignProp:()=>eL,cached:()=>eU,captureStackTrace:()=>e$,cleanEnum:()=>tn,cleanRegex:()=>eO,clone:()=>eF,createTransparentProxy:()=>eG,defineLazy:()=>eD,esc:()=>eN,escapeRegex:()=>eW,extend:()=>e6,finalizeIssue:()=>te,floatSafeRemainder:()=>eP,getElementAtPath:()=>eZ,getEnumValues:()=>eS,getLengthableOrigin:()=>tr,getParsedType:()=>eB,getSizableOrigin:()=>tt,isObject:()=>ez,isPlainObject:()=>eV,issue:()=>to,joinValues:()=>e_,jsonStringifyReplacer:()=>eR,merge:()=>e5,normalizeParams:()=>eJ,nullish:()=>eI,numKeys:()=>eq,omit:()=>e2,optionalKeys:()=>eY,partial:()=>e4,pick:()=>e1,prefixIssues:()=>e9,primitiveTypes:()=>eM,promiseAllObject:()=>ej,propertyKeyTypes:()=>eK,randomString:()=>eC,required:()=>e8,stringifyPrimitive:()=>eQ,unwrapMessage:()=>e7};for(var ev in eb)Q(ew,ev,{get:eb[ev],enumerable:!0});function eE(e){return e}function eA(e){return e}function ex(e){}function eT(e){throw Error()}function ek(e){}function eS(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function e_(e,t="|"){return e.map(e=>eQ(e)).join(t)}function eR(e,t){return"bigint"==typeof t?t.toString():t}function eU(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function eI(e){return null==e}function eO(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function eP(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}function eD(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function eL(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function eZ(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function ej(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let o=0;o<t.length;o++)r[t[o]]=e[o];return r})}function eC(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function eN(e){return JSON.stringify(e)}var e$=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function ez(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var eH=eU(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function eV(e){if(!1===ez(e))return!1;let t=e.constructor;if(void 0===t)return!0;let r=t.prototype;return!1!==ez(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function eq(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var eB=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("undefined"!=typeof Map&&e instanceof Map)return"map";if("undefined"!=typeof Set&&e instanceof Set)return"set";if("undefined"!=typeof Date&&e instanceof Date)return"date";if("undefined"!=typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},eK=new Set(["string","number","symbol"]),eM=new Set(["string","number","bigint","boolean","symbol","undefined"]);function eW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eF(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function eJ(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function eG(e){let t;return new Proxy({},{get:(r,o,n)=>(t??(t=e()),Reflect.get(t,o,n)),set:(r,o,n,i)=>(t??(t=e()),Reflect.set(t,o,n,i)),has:(r,o)=>(t??(t=e()),Reflect.has(t,o)),deleteProperty:(r,o)=>(t??(t=e()),Reflect.deleteProperty(t,o)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,o)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)),defineProperty:(r,o,n)=>(t??(t=e()),Reflect.defineProperty(t,o,n))})}function eQ(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function eY(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}var eX={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},e0={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function e1(e,t){let r={},o=e._zod.def;for(let e in t){if(!(e in o.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=o.shape[e])}return eF(e,{...e._zod.def,shape:r,checks:[]})}function e2(e,t){let r={...e._zod.def.shape},o=e._zod.def;for(let e in t){if(!(e in o.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return eF(e,{...e._zod.def,shape:r,checks:[]})}function e6(e,t){if(!eV(t))throw Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let r={...e._zod.def.shape,...t};return eL(this,"shape",r),r},checks:[]};return eF(e,r)}function e5(e,t){return eF(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return eL(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function e4(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let t in r){if(!(t in o))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:o[t]}):o[t])}else for(let t in o)n[t]=e?new e({type:"optional",innerType:o[t]}):o[t];return eF(t,{...t._zod.def,shape:n,checks:[]})}function e8(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:o[t]}))}else for(let t in o)n[t]=new e({type:"nonoptional",innerType:o[t]});return eF(t,{...t._zod.def,shape:n,checks:[]})}function e3(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function e9(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function e7(e){return"string"==typeof e?e:e?.message}function te(e,t,r){let o={...e,path:e.path??[]};return e.message||(o.message=e7(e.inst?._zod.def?.error?.(e))??e7(t?.error?.(e))??e7(r.customError?.(e))??e7(r.localeError?.(e))??"Invalid input"),delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function tt(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function tr(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function to(...e){let[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}function tn(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ti=class{constructor(...e){}},ts=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,eR,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ta=eh("$ZodError",ts),tc=eh("$ZodError",ts,{Parent:Error}),td=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new em;return i.issues.length?{success:!1,error:new(e??ta)(i.issues.map(e=>te(e,n,eg())))}:{success:!0,data:i.value}},tl=td(tc),tu=e=>async(t,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>te(e,n,eg())))}:{success:!0,data:i.value}},tp=tu(tc),tf=eh("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),th=eh("$ZodCheckMaxLength",(e,t)=>{var r;tf.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eI(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let o=r.value;if(o.length<=t.maximum)return;let n=tr(o);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tm=eh("$ZodCheckMinLength",(e,t)=>{var r;tf.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eI(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let o=r.value;if(o.length>=t.minimum)return;let n=tr(o);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ty=eh("$ZodCheckLengthEquals",(e,t)=>{var r;tf.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eI(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let o=r.value,n=o.length;if(n===t.length)return;let i=tr(o),s=n>t.length;r.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),tg=eh("$ZodCheckOverwrite",(e,t)=>{tf.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),tw=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},tb={major:4,minor:0,patch:0},tv=eh("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=tb;let o=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&o.unshift(e),o))for(let r of t._zod.onattach)r(e);if(0===o.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let o,n=e3(e);for(let i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(n)continue;let t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new em;if(o||s instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(n||(n=e3(e,t)))});else{if(e.issues.length===t)continue;n||(n=e3(e,t))}}return o?o.then(()=>e):e};e._zod.run=(r,n)=>{let i=e._zod.parse(r,n);if(i instanceof Promise){if(!1===n.async)throw new em;return i.then(e=>t(e,o,n))}return t(i,o,n)}}e["~standard"]={validate:t=>{try{let r=tl(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return tp(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),tE=eh("$ZodUnknown",(e,t)=>{tv.init(e,t),e._zod.parse=e=>e}),tA=eh("$ZodNever",(e,t)=>{tv.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function tx(e,t,r){e.issues.length&&t.issues.push(...e9(r,e.issues)),t.value[r]=e.value}var tT=eh("$ZodArray",(e,t)=>{tv.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let e=0;e<n.length;e++){let s=n[e],a=t.element._zod.run({value:s,issues:[]},o);a instanceof Promise?i.push(a.then(t=>tx(t,r,e))):tx(a,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function tk(e,t,r){e.issues.length&&t.issues.push(...e9(r,e.issues)),t.value[r]=e.value}function tS(e,t,r,o){e.issues.length?void 0===o[r]?r in o?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...e9(r,e.issues)):void 0===e.value?r in o&&(t.value[r]=void 0):t.value[r]=e.value}function t_(e,t,r,o){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>te(e,o,eg())))}),t}(e,t)=>{let r,o;tv.init(e,t);let n=eU(()=>{let e=Object.keys(t.shape);for(let r of e)if(!(t.shape[r]instanceof tv))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=eY(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});eD(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let o=e[t]._zod;if(o.values)for(let e of(r[t]??(r[t]=new Set),o.values))r[t].add(e)}return r});let i=!ey.jitless,s=i&&eH.value,a=t.catchall;e._zod.parse=(c,d)=>{o??(o=n.value);let l=c.value;if(!ez(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c;let u=[];
1if(i&&s&&d?.async===!1&&!0!==d.jitless)r||(r=(e=>{let t=new tw(["shape","payload","ctx"]),r=n.value,o=e=>{let t=eN(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),s=0;for(let e of r.keys)i[e]=`key_${s++}`;for(let e of(t.write("const newResult = {}"),r.keys))if(r.optionalKeys.has(e)){let r=i[e];t.write(`const ${r} = ${o(e)};`);let n=eN(e);t.write(` 2 if (${r}.issues.length) { 3 if (input[${n}] === undefined) { 4 if (${n} in input) { 5 newResult[${n}] = undefined; 6 } 7 } else { 8 payload.issues = payload.issues.concat( 9 ${r}.issues.map((iss) => ({ 10 ...iss, 11 path: iss.path ? [${n}, ...iss.path] : [${n}], 12 })) 13 ); 14 } 15 } else if (${r}.value === undefined) { 16 if (${n} in input) newResult[${n}] = undefined; 17 } else { 18 newResult[${n}] = ${r}.value; 19 } 20 `)}else{let r=i[e];t.write(`const ${r} = ${o(e)};`),t.write(` 21 if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({ 22 ...iss, 23 path: iss.path ? [${eN(e)}, ...iss.path] : [${eN(e)}] 24 })));`),t.write(`newResult[${eN(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");let a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),c=r(c,d);else{c.value={};let e=o.shape;for(let t of o.keys){let r=e[t],o=r._zod.run({value:l[t],issues:[]},d),n="optional"===r._zod.optin&&"optional"===r._zod.optout;o instanceof Promise?u.push(o.then(e=>n?tS(e,c,t,l):tk(e,c,t))):n?tS(o,c,t,l):tk(o,c,t)}}if(!a)return u.length?Promise.all(u).then(()=>c):c;let p=[],f=o.keySet,h=a._zod,m=h.def.type;
24for(let e of Object.keys(l)){if(f.has(e))continue;if("never"===m){p.push(e);continue}let t=h.run({value:l[e],issues:[]},d);t instanceof Promise?u.push(t.then(t=>tk(t,c,e))):tk(t,c,e)}return(p.length&&c.issues.push({code:"unrecognized_keys",keys:p,input:l,inst:e}),u.length)?Promise.all(u).then(()=>c):c}};var tR=eh("$ZodUnion",(e,t)=>{tv.init(e,t),eD(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),eD(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),eD(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),eD(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>eO(e.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1,i=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)i.push(t),n=!0;else{if(0===t.issues.length)return t;i.push(t)}}return n?Promise.all(i).then(t=>t_(t,r,e,o)):t_(i,r,e,o)}}),tU=eh("$ZodIntersection",(e,t)=>{tv.init(e,t),e._zod.parse=(e,r)=>{let o=e.value,n=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([t,r])=>tI(e,t,r)):tI(e,n,i)}});function tI(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),e3(e))return e;let o=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(eV(t)&&eV(r)){let o=Object.keys(r),n=Object.keys(t).filter(e=>-1!==o.indexOf(e)),i={...t,...r};for(let o of n){let n=e(t[o],r[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};i[o]=n.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let o=[];for(let n=0;n<t.length;n++){let i=e(t[n],r[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};o.push(i.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var tO=eh("$ZodEnum",(e,t)=>{tv.init(e,t);let r=eS(t.entries);e._zod.values=new Set(r),e._zod.pattern=RegExp(`^(${r.filter(e=>eK.has(typeof e)).map(e=>"string"==typeof e?eW(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{let n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),tP=eh("$ZodTransform",(e,t)=>{tv.init(e,t),e._zod.parse=(e,r)=>{let o=t.transform(e.value,e);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(t=>(e.value=t,e));if(o instanceof Promise)throw new em;return e.value=o,e}}),tD=eh("$ZodOptional",(e,t)=>{tv.init(e,t),e._zod.optin="optional",e._zod.optout="optional",eD(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),eD(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${eO(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),tL=eh("$ZodNullable",(e,t)=>{tv.init(e,t),eD(e._zod,"optin",()=>t.innerType._zod.optin),eD(e._zod,"optout",()=>t.innerType._zod.optout),eD(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${eO(e.source)}|null)$`):void 0}),eD(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),tZ=eh("$ZodDefault",(e,t)=>{tv.init(e,t),e._zod.optin="optional",eD(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;let o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(e=>tj(e,t)):tj(o,t)}});function tj(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var tC=eh("$ZodPrefault",(e,t)=>{tv.init(e,t),e._zod.optin="optional",eD(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),tN=eh("$ZodNonOptional",(e,t)=>{tv.init(e,t),eD(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(t=>t$(t,e)):t$(n,e)}});function t$(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var tz=eh("$ZodCatch",(e,t)=>{tv.init(e,t),e._zod.optin="optional",eD(e._zod,"optout",()=>t.innerType._zod.optout),eD(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{let o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(o=>(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>te(e,r,eg()))},input:e.value}),e.issues=[]),e)):(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>te(e,r,eg()))},input:e.value}),e.issues=[]),e)}}),tH=eh("$ZodPipe",(e,t)=>{tv.init(e,t),eD(e._zod,"values",()=>t.in._zod.values),eD(e._zod,"optin",()=>t.in._zod.optin),eD(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{let o=t.in._zod.run(e,r);return o instanceof Promise?o.then(e=>tV(e,t,r)):tV(o,t,r)}});function tV(e,t,r){return e3(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var tq=eh("$ZodReadonly",(e,t)=>{tv.init(e,t),eD(e._zod,"propValues",()=>t.innerType._zod.propValues),eD(e._zod,"values",()=>t.innerType._zod.values),eD(e._zod,"optin",()=>t.innerType._zod.optin),eD(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{let o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(tB):tB(o)}});function tB(e){return e.value=Object.freeze(e.value),e}var tK=eh("$ZodCustom",(e,t)=>{tf.init(e,t),tv.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(t=>tM(t,r,o,e));tM(n,r,o,e)}});function tM(e,t,r,o){if(!e){let e={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(e.params=o._zod.def.params),t.issues.push(to(e))}}Symbol("ZodOutput"),Symbol("ZodInput");var tW=new class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function tF(e,t){return new tm({check:"min_length",...eJ(t),minimum:e})}var tJ=(e,t)=>
24{ta.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>{let r,o,n;return r=t||function(e){return e.message},o={_errors:[]},(n=e=>{for(let t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)o._errors.push(r(t));else{let e=o,n=0;for(;n<t.path.length;){let o=t.path[n];n===t.path.length-1?(e[o]=e[o]||{_errors:[]},e[o]._errors.push(r(t))):e[o]=e[o]||{_errors:[]},e=e[o],n++}}})(e),o}},flatten:{value:t=>(function(e,t=e=>e.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}})(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})};eh("ZodError",tJ);var tG=eh("ZodError",tJ,{Parent:Error}),tQ=(e,t,r,o)=>{let n=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},n);if(i instanceof Promise)throw new em;if(i.issues.length){let e=new(o?.Err??tG)(i.issues.map(e=>te(e,n,eg())));throw e$(e,o?.callee),e}return i.value},tY=async(e,t,r,o)=>{let n=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:t,issues:[]},n);if(i instanceof Promise&&(i=await i),i.issues.length){let e=new(o?.Err??tG)(i.issues.map(e=>te(e,n,eg())));throw e$(e,o?.callee),e}return i.value},tX=td(tG),t0=tu(tG),t1=eh("ZodType",(e,t)=>(tv.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>eF(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>tQ(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>tX(e,t,r),e.parseAsync=async(t,r)=>tY(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>t0(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return new rd({type:"custom",check:"custom",fn:e,...eJ(t)})}(t,r)),e.superRefine=t=>{var r,o;let n,i;return e.check((r=t,i=(o=e=>(e.addIssue=t=>{"string"==typeof t?e.issues.push(ew.issue(t,e.value,i._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=e.value),t.inst??(t.inst=i),t.continue??(t.continue=!i._zod.def.abort),e.issues.push(ew.issue(t)))},r(e.value,e)),(n=new tf({check:"custom"}))._zod.check=o,n)))},e.overwrite=t=>e.check(new tg({check:"overwrite",tx:t})),e.optional=()=>t7(e),e.nullable=()=>rt(e),e.nullish=()=>t7(rt(e)),e.nonoptional=t=>{var r,o;return r=e,o=t,new rn({type:"nonoptional",innerType:r,...ew.normalizeParams(o)})},e.array=()=>(function(e,t){return new t6({type:"array",element:e,...eJ(void 0)})})(e),e.or=t=>new t5({type:"union",options:[e,t],...ew.normalizeParams(void 0)}),e.and=t=>{var r;return r=e,new t4({type:"intersection",left:r,right:t})},e.transform=t=>ra(e,new t3({type:"transform",transform:t})),e.default=t=>{var r,o;return r=e,o=t,new rr({type:"default",innerType:r,get defaultValue(){return"function"==typeof o?o():o}})},e.prefault=t=>{var r,o;return r=e,o=t,new ro({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof o?o():o}})},e.catch=t=>{var r;return new ri({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r})},e.pipe=t=>ra(e,t),e.readonly=()=>new rc({type:"readonly",innerType:e}),e.describe=t=>{let r=e.clone();return tW.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>tW.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return tW.get(e);let r=e.clone();return tW.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),t2=eh("ZodUnknown",(e,t)=>{tE.init(e,t),t1.init(e,t)});(e,t)=>{tA.init(e,t),t1.init(e,t)};var t6=eh("ZodArray",(e,t)=>{tT.init(e,t),t1.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(tF(t,r)),e.nonempty=t=>e.check(tF(1,t)),e.max=(t,r)=>e.check(new th({check:"max_length",...eJ(r),maximum:t})),e.length=(t,r)=>e.check(new ty({check:"length_equals",...eJ(r),length:t})),e.unwrap=()=>e.element}),t5=eh("ZodUnion",(e,t)=>{tR.init(e,t),t1.init(e,t),e.options=t.options}),t4=eh("ZodIntersection",(e,t)=>{tU.init(e,t),t1.init(e,t)}),t8=eh("ZodEnum",(e,t)=>{tO.init(e,t),t1.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,o)=>{let n={};for(let o of e)if(r.has(o))n[o]=t.entries[o];else throw Error(`Key ${o} not found in enum`);return new t8({...t,checks:[],...ew.normalizeParams(o),entries:n})},e.exclude=(e,o)=>{let n={...t.entries};for(let t of e)if(r.has(t))delete n[t];else throw Error(`Key ${t} not found in enum`);return new t8({...t,checks:[],...ew.normalizeParams(o),entries:n})}}),t3=eh("ZodTransform",(e,t)=>{tP.init(e,t),t1.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=o=>{"string"==typeof o?r.issues.push(ew.issue(o,r.value,t)):(o.fatal&&(
24o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),r.issues.push(ew.issue(o)))};let n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}}),t9=eh("ZodOptional",(e,t)=>{tD.init(e,t),t1.init(e,t),e.unwrap=()=>e._zod.def.innerType});function t7(e){return new t9({type:"optional",innerType:e})}var re=eh("ZodNullable",(e,t)=>{tL.init(e,t),t1.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rt(e){return new re({type:"nullable",innerType:e})}var rr=eh("ZodDefault",(e,t)=>{tZ.init(e,t),t1.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),ro=eh("ZodPrefault",(e,t)=>{tC.init(e,t),t1.init(e,t),e.unwrap=()=>e._zod.def.innerType}),rn=eh("ZodNonOptional",(e,t)=>{tN.init(e,t),t1.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ri=eh("ZodCatch",(e,t)=>{tz.init(e,t),t1.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),rs=eh("ZodPipe",(e,t)=>{tH.init(e,t),t1.init(e,t),e.in=t.in,e.out=t.out});function ra(e,t){return new rs({type:"pipe",in:e,out:t})}var rc=eh("ZodReadonly",(e,t)=>{tq.init(e,t),t1.init(e,t)}),rd=eh("ZodCustom",(e,t)=>{tK.init(e,t),t1.init(e,t)}),rl=e.i(448969);e.s(["default",0,rl],331243),e.s(["default",0,rl],453267),e.i(453267),e.i(331243),e.s(["$brand",()=>rl.$brand,"$input",()=>rl.$input,"$output",()=>rl.$output,"NEVER",()=>rl.NEVER,"TimePrecision",()=>rl.TimePrecision,"ZodAny",()=>rl.ZodAny,"ZodArray",()=>rl.ZodArray,"ZodBase64",()=>rl.ZodBase64,"ZodBase64URL",()=>rl.ZodBase64URL,"ZodBigInt",()=>rl.ZodBigInt,"ZodBigIntFormat",()=>rl.ZodBigIntFormat,"ZodBoolean",()=>rl.ZodBoolean,"ZodCIDRv4",()=>rl.ZodCIDRv4,"ZodCIDRv6",()=>rl.ZodCIDRv6,"ZodCUID",()=>rl.ZodCUID,"ZodCUID2",()=>rl.ZodCUID2,"ZodCatch",()=>rl.ZodCatch,"ZodCodec",()=>rl.ZodCodec,"ZodCustom",()=>rl.ZodCustom,"ZodCustomStringFormat",()=>rl.ZodCustomStringFormat,"ZodDate",()=>rl.ZodDate,"ZodDefault",()=>rl.ZodDefault,"ZodDiscriminatedUnion",()=>rl.ZodDiscriminatedUnion,"ZodE164",()=>rl.ZodE164,"ZodEmail",()=>rl.ZodEmail,"ZodEmoji",()=>rl.ZodEmoji,"ZodEnum",()=>rl.ZodEnum,"ZodError",()=>rl.ZodError,"ZodFile",()=>rl.ZodFile,"ZodFirstPartyTypeKind",()=>rl.ZodFirstPartyTypeKind,"ZodFunction",()=>
24rl.ZodFunction,"ZodGUID",()=>rl.ZodGUID,"ZodIPv4",()=>rl.ZodIPv4,"ZodIPv6",()=>rl.ZodIPv6,"ZodISODate",()=>rl.ZodISODate,"ZodISODateTime",()=>rl.ZodISODateTime,"ZodISODuration",()=>rl.ZodISODuration,"ZodISOTime",()=>rl.ZodISOTime,"ZodIntersection",()=>rl.ZodIntersection,"ZodIssueCode",()=>rl.ZodIssueCode,"ZodJWT",()=>rl.ZodJWT,"ZodKSUID",()=>rl.ZodKSUID,"ZodLazy",()=>rl.ZodLazy,"ZodLiteral",()=>rl.ZodLiteral,"ZodMap",()=>rl.ZodMap,"ZodNaN",()=>rl.ZodNaN,"ZodNanoID",()=>rl.ZodNanoID,"ZodNever",()=>rl.ZodNever,"ZodNonOptional",()=>rl.ZodNonOptional,"ZodNull",()=>rl.ZodNull,"ZodNullable",()=>rl.ZodNullable,"ZodNumber",()=>rl.ZodNumber,"ZodNumberFormat",()=>rl.ZodNumberFormat,"ZodObject",()=>rl.ZodObject,"ZodOptional",()=>rl.ZodOptional,"ZodPipe",()=>rl.ZodPipe,"ZodPrefault",()=>rl.ZodPrefault,"ZodPromise",()=>rl.ZodPromise,"ZodReadonly",()=>rl.ZodReadonly,"ZodRealError",()=>rl.ZodRealError,"ZodRecord",()=>rl.ZodRecord,"ZodSet",()=>rl.ZodSet,"ZodString",()=>rl.ZodString,"ZodStringFormat",()=>rl.ZodStringFormat,"ZodSuccess",()=>rl.ZodSuccess,"ZodSymbol",()=>rl.ZodSymbol,"ZodTemplateLiteral",()=>rl.ZodTemplateLiteral,"ZodTransform",()=>rl.ZodTransform,"ZodTuple",()=>rl.ZodTuple,"ZodType",()=>rl.ZodType,"ZodULID",()=>rl.ZodULID,"ZodURL",()=>rl.ZodURL,"ZodUUID",()=>rl.ZodUUID,"ZodUndefined",()=>rl.ZodUndefined,"ZodUnion",()=>rl.ZodUnion,"ZodUnknown",()=>rl.ZodUnknown,"ZodVoid",()=>rl.ZodVoid,"ZodXID",()=>rl.ZodXID,"_ZodString",()=>rl._ZodString,"_default",()=>rl._default,"_function",()=>rl._function,"any",()=>rl.any,"array",()=>rl.array,"base64",()=>rl.base64,"base64url",()=>rl.base64url,"bigint",()=>rl.bigint,"boolean",()=>rl.boolean,"catch",()=>rl.catch,"check",()=>rl.check,"cidrv4",()=>rl.cidrv4,"cidrv6",()=>rl.cidrv6,"clone",()=>rl.clone,"codec",()=>rl.codec,"coerce",()=>rl.coerce,"config",()=>rl.config,"core",()=>rl.core,"cuid",()=>rl.cuid,"cuid2",()=>rl.cuid2,"custom",()=>rl.custom,"date",()=>rl.date,"decode",()=>rl.decode,"decodeAsync",()=>rl.decodeAsync,"default",0,rl,"discriminatedUnion",()=>rl.discriminatedUnion,"e164",()=>rl.e164,"email",()=>rl.email,"emoji",()=>rl.emoji,"encode",()=>rl.encode,"encodeAsync",()=>rl.encodeAsync,"endsWith",()=>rl.endsWith,"enum",()=>rl.enum,"file",()=>rl.file,"flattenError",()=>rl.flattenError,"float32",()=>rl.float32,"float64",()=>rl.float64,"formatError",()=>rl.formatError,"function",()=>rl.function,"getErrorMap",()=>rl.getErrorMap,"globalRegistry",()=>rl.globalRegistry,"gt",()=>rl.gt,"gte",()=>rl.gte,"guid",()=>rl.guid,"hash",()=>rl.hash,"hex",()=>rl.hex,"hostname",()=>rl.hostname,"httpUrl",()=>rl.httpUrl,"includes",()=>rl.includes,"instanceof",()=>rl.instanceof,"int",()=>rl.int,"int32",()=>rl.int32,"int64",()=>rl.int64,"intersection",()=>rl.intersection,"ipv4",()=>rl.ipv4,"ipv6",()=>rl.ipv6,"iso",()=>rl.iso,"json",()=>rl.json,"jwt",()=>rl.jwt,"keyof",()=>rl.keyof,"ksuid",()=>rl.ksuid,"lazy",()=>rl.lazy,"length",()=>rl.length,"literal",()=>rl.literal,"locales",()=>rl.locales,"looseObject",()=>rl.looseObject,"lowercase",()=>rl.lowercase,"lt",()=>rl.lt,"lte",()=>rl.lte,"map",()=>rl.map,"maxLength",()=>rl.maxLength,"maxSize",()=>rl.maxSize,"mime",()=>rl.mime,"minLength",()=>rl.minLength,"minSize",()=>rl.minSize,"multipleOf",()=>rl.multipleOf,"nan",()=>rl.nan,"nanoid",()=>rl.nanoid,"nativeEnum",()=>rl.nativeEnum,"negative",()=>rl.negative,"never",()=>rl.never,"nonnegative",()=>rl.nonnegative,"nonoptional",()=>rl.nonoptional,"nonpositive",()=>rl.nonpositive,"normalize",()=>rl.normalize,"null",()=>rl.null,"nullable",()=>rl.nullable,"nullish",()=>rl.nullish,"number",()=>rl.number,"object",()=>rl.object,"optional",()=>rl.optional,"overwrite",()=>rl.overwrite,"parse",()=>rl.parse,"parseAsync",()=>rl.parseAsync,"partialRecord",()=>rl.partialRecord,"pipe",()=>rl.pipe,"positive",()=>rl.positive,"prefault",()=>rl.prefault,"preprocess",()=>rl.preprocess,"prettifyError",()=>rl.prettifyError,"promise",()=>rl.promise,"property",()=>rl.property,"readonly",()=>rl.readonly,"record",()=>rl.record,"refine",()=>rl.refine,"regex",()=>rl.regex,"regexes",()=>rl.regexes,"registry",()=>rl.registry,"safeDecode",()=>rl.safeDecode,"safeDecodeAsync",()=>rl.safeDecodeAsync,"safeEncode",()=>rl.safeEncode,"safeEncodeAsync",()=>rl.safeEncodeAsync,"safeParse",()=>rl.safeParse,"safeParseAsync",()=>rl.safeParseAsync,"set",()=>rl.set,"setErrorMap",()=>rl.setErrorMap,"size",()=>rl.size,"startsWith",()=>rl.startsWith,"strictObject",()=>rl.strictObject,"string",()=>
24rl.string,"stringFormat",()=>rl.stringFormat,"stringbool",()=>rl.stringbool,"success",()=>rl.success,"superRefine",()=>rl.superRefine,"symbol",()=>rl.symbol,"templateLiteral",()=>rl.templateLiteral,"toJSONSchema",()=>rl.toJSONSchema,"toLowerCase",()=>rl.toLowerCase,"toUpperCase",()=>rl.toUpperCase,"transform",()=>rl.transform,"treeifyError",()=>rl.treeifyError,"trim",()=>rl.trim,"tuple",()=>rl.tuple,"uint32",()=>rl.uint32,"uint64",()=>rl.uint64,"ulid",()=>rl.ulid,"undefined",()=>rl.undefined,"union",()=>rl.union,"unknown",()=>rl.unknown,"uppercase",()=>rl.uppercase,"url",()=>rl.url,"util",()=>rl.util,"uuid",()=>rl.uuid,"uuidv4",()=>rl.uuidv4,"uuidv6",()=>rl.uuidv6,"uuidv7",()=>rl.uuidv7,"void",()=>rl.void,"xid",()=>rl.xid,"z",0,rl],260465),e.i(260465),e.s(["$brand",()=>rl.$brand,"$input",()=>rl.$input,"$output",()=>rl.$output,"NEVER",()=>rl.NEVER,"TimePrecision",()=>rl.TimePrecision,"ZodAny",()=>rl.ZodAny,"ZodArray",()=>rl.ZodArray,"ZodBase64",()=>rl.ZodBase64,"ZodBase64URL",()=>rl.ZodBase64URL,"ZodBigInt",()=>rl.ZodBigInt,"ZodBigIntFormat",()=>rl.ZodBigIntFormat,"ZodBoolean",()=>rl.ZodBoolean,"ZodCIDRv4",()=>rl.ZodCIDRv4,"ZodCIDRv6",()=>rl.ZodCIDRv6,"ZodCUID",()=>rl.ZodCUID,"ZodCUID2",()=>rl.ZodCUID2,"ZodCatch",()=>rl.ZodCatch,"ZodCodec",()=>rl.ZodCodec,"ZodCustom",()=>rl.ZodCustom,"ZodCustomStringFormat",()=>rl.ZodCustomStringFormat,"ZodDate",()=>rl.ZodDate,"ZodDefault",()=>rl.ZodDefault,"ZodDiscriminatedUnion",()=>rl.ZodDiscriminatedUnion,"ZodE164",()=>rl.ZodE164,"ZodEmail",()=>rl.ZodEmail,"ZodEmoji",()=>rl.ZodEmoji,"ZodEnum",()=>rl.ZodEnum,"ZodError",()=>rl.ZodError,"ZodFile",()=>rl.ZodFile,"ZodFirstPartyTypeKind",()=>rl.ZodFirstPartyTypeKind,"ZodFunction",()=>
24rl.ZodFunction,"ZodGUID",()=>rl.ZodGUID,"ZodIPv4",()=>rl.ZodIPv4,"ZodIPv6",()=>rl.ZodIPv6,"ZodISODate",()=>rl.ZodISODate,"ZodISODateTime",()=>rl.ZodISODateTime,"ZodISODuration",()=>rl.ZodISODuration,"ZodISOTime",()=>rl.ZodISOTime,"ZodIntersection",()=>rl.ZodIntersection,"ZodIssueCode",()=>rl.ZodIssueCode,"ZodJWT",()=>rl.ZodJWT,"ZodKSUID",()=>rl.ZodKSUID,"ZodLazy",()=>rl.ZodLazy,"ZodLiteral",()=>rl.ZodLiteral,"ZodMap",()=>rl.ZodMap,"ZodNaN",()=>rl.ZodNaN,"ZodNanoID",()=>rl.ZodNanoID,"ZodNever",()=>rl.ZodNever,"ZodNonOptional",()=>rl.ZodNonOptional,"ZodNull",()=>rl.ZodNull,"ZodNullable",()=>rl.ZodNullable,"ZodNumber",()=>rl.ZodNumber,"ZodNumberFormat",()=>rl.ZodNumberFormat,"ZodObject",()=>rl.ZodObject,"ZodOptional",()=>rl.ZodOptional,"ZodPipe",()=>rl.ZodPipe,"ZodPrefault",()=>rl.ZodPrefault,"ZodPromise",()=>rl.ZodPromise,"ZodReadonly",()=>rl.ZodReadonly,"ZodRealError",()=>rl.ZodRealError,"ZodRecord",()=>rl.ZodRecord,"ZodSet",()=>rl.ZodSet,"ZodString",()=>rl.ZodString,"ZodStringFormat",()=>rl.ZodStringFormat,"ZodSuccess",()=>rl.ZodSuccess,"ZodSymbol",()=>rl.ZodSymbol,"ZodTemplateLiteral",()=>rl.ZodTemplateLiteral,"ZodTransform",()=>rl.ZodTransform,"ZodTuple",()=>rl.ZodTuple,"ZodType",()=>rl.ZodType,"ZodULID",()=>rl.ZodULID,"ZodURL",()=>rl.ZodURL,"ZodUUID",()=>rl.ZodUUID,"ZodUndefined",()=>rl.ZodUndefined,"ZodUnion",()=>rl.ZodUnion,"ZodUnknown",()=>rl.ZodUnknown,"ZodVoid",()=>rl.ZodVoid,"ZodXID",()=>rl.ZodXID,"_ZodString",()=>rl._ZodString,"_default",()=>rl._default,"_function",()=>rl._function,"any",()=>rl.any,"array",()=>rl.array,"base64",()=>rl.base64,"base64url",()=>rl.base64url,"bigint",()=>rl.bigint,"boolean",()=>rl.boolean,"catch",()=>rl.catch,"check",()=>rl.check,"cidrv4",()=>rl.cidrv4,"cidrv6",()=>rl.cidrv6,"clone",()=>rl.clone,"codec",()=>rl.codec,"coerce",()=>rl.coerce,"config",()=>rl.config,"core",()=>rl.core,"cuid",()=>rl.cuid,"cuid2",()=>rl.cuid2,"custom",()=>rl.custom,"date",()=>rl.date,"decode",()=>rl.decode,"decodeAsync",()=>rl.decodeAsync,"default",0,rl,"discriminatedUnion",()=>rl.discriminatedUnion,"e164",()=>rl.e164,"email",()=>rl.email,"emoji",()=>rl.emoji,"encode",()=>rl.encode,"encodeAsync",()=>rl.encodeAsync,"endsWith",()=>rl.endsWith,"enum",()=>rl.enum,"file",()=>rl.file,"flattenError",()=>rl.flattenError,"float32",()=>rl.float32,"float64",()=>rl.float64,"formatError",()=>rl.formatError,"function",()=>rl.function,"getErrorMap",()=>rl.getErrorMap,"globalRegistry",()=>rl.globalRegistry,"gt",()=>rl.gt,"gte",()=>rl.gte,"guid",()=>rl.guid,"hash",()=>rl.hash,"hex",()=>rl.hex,"hostname",()=>rl.hostname,"httpUrl",()=>rl.httpUrl,"includes",()=>rl.includes,"instanceof",()=>rl.instanceof,"int",()=>rl.int,"int32",()=>rl.int32,"int64",()=>rl.int64,"intersection",()=>rl.intersection,"ipv4",()=>rl.ipv4,"ipv6",()=>rl.ipv6,"iso",()=>rl.iso,"json",()=>rl.json,"jwt",()=>rl.jwt,"keyof",()=>rl.keyof,"ksuid",()=>rl.ksuid,"lazy",()=>rl.lazy,"length",()=>rl.length,"literal",()=>rl.literal,"locales",()=>rl.locales,"looseObject",()=>rl.looseObject,"lowercase",()=>rl.lowercase,"lt",()=>rl.lt,"lte",()=>rl.lte,"map",()=>rl.map,"maxLength",()=>rl.maxLength,"maxSize",()=>rl.maxSize,"mime",()=>rl.mime,"minLength",()=>rl.minLength,"minSize",()=>rl.minSize,"multipleOf",()=>rl.multipleOf,"nan",()=>rl.nan,"nanoid",()=>rl.nanoid,"nativeEnum",()=>rl.nativeEnum,"negative",()=>rl.negative,"never",()=>rl.never,"nonnegative",()=>rl.nonnegative,"nonoptional",()=>rl.nonoptional,"nonpositive",()=>rl.nonpositive,"normalize",()=>rl.normalize,"null",()=>rl.null,"nullable",()=>rl.nullable,"nullish",()=>rl.nullish,"number",()=>rl.number,"object",()=>rl.object,"optional",()=>rl.optional,"overwrite",()=>rl.overwrite,"parse",()=>rl.parse,"parseAsync",()=>rl.parseAsync,"partialRecord",()=>rl.partialRecord,"pipe",()=>rl.pipe,"positive",()=>rl.positive,"prefault",()=>rl.prefault,"preprocess",()=>rl.preprocess,"prettifyError",()=>rl.prettifyError,"promise",()=>rl.promise,"property",()=>rl.property,"readonly",()=>rl.readonly,"record",()=>rl.record,"refine",()=>rl.refine,"regex",()=>rl.regex,"regexes",()=>rl.regexes,"registry",()=>rl.registry,"safeDecode",()=>rl.safeDecode,"safeDecodeAsync",()=>rl.safeDecodeAsync,"safeEncode",()=>rl.safeEncode,"safeEncodeAsync",()=>rl.safeEncodeAsync,"safeParse",()=>rl.safeParse,"safeParseAsync",()=>rl.safeParseAsync,"set",()=>rl.set,"setErrorMap",()=>rl.setErrorMap,"size",()=>rl.size,"startsWith",()=>rl.startsWith,"strictObject",()=>rl.strictObject,"string",()=>
24rl.string,"stringFormat",()=>rl.stringFormat,"stringbool",()=>rl.stringbool,"success",()=>rl.success,"superRefine",()=>rl.superRefine,"symbol",()=>rl.symbol,"templateLiteral",()=>rl.templateLiteral,"toJSONSchema",()=>rl.toJSONSchema,"toLowerCase",()=>rl.toLowerCase,"toUpperCase",()=>rl.toUpperCase,"transform",()=>rl.transform,"treeifyError",()=>rl.treeifyError,"trim",()=>rl.trim,"tuple",()=>rl.tuple,"uint32",()=>rl.uint32,"uint64",()=>rl.uint64,"ulid",()=>rl.ulid,"undefined",()=>rl.undefined,"union",()=>rl.union,"unknown",()=>rl.unknown,"uppercase",()=>rl.uppercase,"url",()=>rl.url,"util",()=>rl.util,"uuid",()=>rl.uuid,"uuidv4",()=>rl.uuidv4,"uuidv6",()=>rl.uuidv6,"uuidv7",()=>rl.uuidv7,"void",()=>rl.void,"xid",()=>rl.xid,"z",()=>rl],926919),e.i(926919);var ru=e.i(580588),ru=ru;let rp=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e));function rf(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function rh(e,t,r){let o="",n=0,i=0;for(let r of e)for(n=n<<8|r,i+=8;i>=6;)i-=6,o+=t[n>>i&63];if(i>0&&(o+=t[n<<6-i&63]),r){let e=(4-o.length%4)%4;o+="=".repeat(e)}return o}function rm(e,t){let r=new Map;for(let e=0;e<t.length;e++)r.set(t[e],e);let o=[],n=0,i=0;for(let t of e){if("="===t)break;let e=r.get(t);if(void 0===e)throw Error(`Invalid Base64 character: ${t}`);n=n<<6|e,(i+=6)>=8&&(i-=8,o.push(n>>i&255))}return Uint8Array.from(o)}let ry={encode(e,t={}){let r=rf(!1);return rh("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){"string"!=typeof e&&(e=new TextDecoder().decode(e));let t=rf(e.includes("-")||e.includes("_"));return rm(e,t)}},rg={encode(e,t={}){let r=rf(!0);return rh("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){let t=rf(e.includes("-")||e.includes("_"));return rm(e,t)}},rw=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>J.importKey("raw","string"==typeof t?new TextEncoder().encode(t):t,{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,o)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let n=await J.sign("HMAC",e,"string"==typeof o?new TextEncoder().encode(o):o);return"hex"===t?(e=>{if("string"==typeof e&&(e=new TextEncoder().encode(e)),0===e.byteLength)return"";let t=new Uint8Array(e),r="";for(let e of t)r+=e.toString(16).padStart(2,"0");return r})(n):"base64"===t||"base64url"===t||"base64urlnopad"===t?rg.encode(n,{padding:"base64urlnopad"!==t}):n},verify:async(e,o,n)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(n=(e=>{if(!e)return"";if("string"==typeof e){if(e.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(e))throw Error("Invalid hexadecimal string");let 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)})(n)),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(n=await ry.decode(n)),J.verify("HMAC",e,"string"==typeof n?new TextEncoder().encode(n):n,"string"==typeof o?new TextEncoder().encode(o):o))};return r},rb=["info","success","warn","error","debug"],rv="\x1b[0m",rE="\x1b[31m",rA="\x1b[32m",rx="\x1b[33m",rT="\x1b[34m",rk="\x1b[35m",rS={info:rT,success:rA,warn:rx,error:rE,debug:rk},r_=(o=a?.disabled!==!0,n=a?.level??"error",{...Object.fromEntries(rb.map(e=>[e,(...[t,...r])=>((e,t,r=[])=>{let i;if(!o||!(rb.indexOf(e)<=rb.indexOf(n)))return;let s=(i=new Date().toISOString(),`\x1b[2m${i}${rv} ${rS[e]}${e.toUpperCase()}${rv} \x1b[1m[Better Auth]:${rv} ${t}`);a&&"function"==typeof a.log?a.log("success"===e?"info":e,t,...r):"error"===e?console.error(s,...r):"warn"===e?console.warn(s,...r):console.log(s,...r)})(e,t,r)])),get level(){return n}});function rR(e){try{if("string"!=typeof e)return e;return JSON.parse(e,function(e,t){if("string"==typeof t&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t})}catch(e){return r_.error("Error parsing JSON",{error:e}),null}}function rU(e,t="/api/auth"){return!function(e){try{let t=new URL(e);return"/"!==t.pathname}catch(t){throw new B(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e)?(t=t.startsWith("/")?t:`/${t}`,`${e.replace(/\/+$/,"")}${t}`):e}function rI(e){try{return new URL(e).origin}catch(e){return null}}function rO(e){try{return new URL(e).protocol}catch(e){return null}}function rP(e){try{return new URL(e).host}catch(t){return e}}let rD=new Map,rL={decode:(e,t="utf-8")=>(rD.has(t)||rD.set(t,new TextDecoder(t)),rD.get(t).decode(e)),encode:new TextEncoder().encode};async function rZ(e,t){if(e.context.options.session?.cookieCache?.enabled){let r={session:Object.entries(t.session).reduce((t,[r,o])=>{let n=e.context.options.session?.additionalFields?.[r];return n&&!1===n.returned||(t[r]=o),t},{}),user:t.user},o=rp(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),n=rg.encode(JSON.stringify({session:r,expiresAt:o,signature:await rw("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...r,expiresAt:o}))}),{padding:!1});if(n.length>4093)throw new B("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,n,e.context.authCookies.sessionData.options)}}async function rj(e,t,r,o){let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!n;let i=e.context.authCookies.sessionToken.options,s=r?void 0:e.context.sessionConfig.expires
24In;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:s,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await rZ(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function rC(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}),t||e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var ru=ru;let rN=ep(async()=>({})),r$=ep.create({use:[rN,ep(async()=>({}))]}),rz=ef.create({use:[rN]}),rH="Failed to get session",rV="Invalid password",rq="Invalid email or password",rB="Provider not found",rK="Invalid token",rM="id_token not supported",rW="Failed to get user info",rF="User email not found",rJ="Email not verified",rG="Password too short",rQ="Password too long",rY="Credential account not found",rX=W.optional(W.object({disableCookieCache:ru.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:ru.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),r0=async(e,t)=>{if(e.context.session)return e.context.session;let r=await rz("/get-session",{method:"GET",query:rX,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=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return null;let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?rR(rL.decode(rg.decode(r))):null;if(o&&!await rw("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...o.session,expiresAt:o.expiresAt}),o.signature)){let t=e.context.authCookies.sessionData.name;return e.setCookie(t,"",{maxAge:0}),e.json(null)}let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let t=o.session;if(!(o.expiresAt<Date.now()||t.session.expiresAt<new Date))return e.context.session=t,e.json(t);{let t=e.context.authCookies.sessionData.name;e.setCookie(t,"",{maxAge:0})}}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return rC(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-1e3*s+1e3*a<=Date.now()&&(!e.query?.disableRefresh||!e.context.options.session?.disableSessionRefresh)){let t=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:rp(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)return rC(e),e.json(null,{status:401});let r=(t.expiresAt.valueOf()-Date.now())/1e3;return await rj(e,{session:t,user:i.user},!1,{maxAge:r}),e.json({session:t,user:i.user})}return await rZ(e,i),e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new X("INTERNAL_SERVER_ERROR",{message:rH})}})({...e,asResponse:!1,headers:e.headers,returnHeaders:!1,query:{...t,...e.query}}).catch(e=>null);return e.context.session=r,r},r1=r$(async e=>{let t=await r0(e);if(!t?.session)throw new X("UNAUTHORIZED");return{session:t}});r$(async e=>{let t=await r0(e);if(!t?.session&&(e.request||e.headers))throw new X("UNAUTHORIZED");return{session:t}});let r2=r$(async e=>{let t=await r0(e);if(!t?.session)throw new X("UNAUTHORIZED");if(0===e.context.sessionConfig.freshAge)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-o<1e3*r))throw new X("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});function r6(e,t){return{digest:async r=>{let o=new TextEncoder,n="string"==typeof r?o.encode(r):r,i=await J.digest(e,n);return"hex"===t?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join(""):"base64"===t||"base64url"===t||"base64urlnopad"===t?t.includes("url")?rg.encode(i,{padding:"base64urlnopad"!==t}):ry.encode(i):i}}}function r5(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function r4(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function r8(e,t,r=""){let o=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name,n=e?.length,i=void 0!==t;if(!o||i&&n!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(o?`length=${n}`:`type=${typeof e}`));return e}function r3(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function r9(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function r7(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}rz("/revoke-session",{method:"POST",body:W.object({token:W.string().meta({description:"The token to revoke"})}),use:[r1],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=>
24{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new X("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new X("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),new X("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),rz("/revoke-sessions",{method:"POST",use:[r1],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&&"object"==typeof t&&"name"in t?t.name:"",t),new X("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),rz("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[r1],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new X("UNAUTHORIZED");let r=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(r.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});let oe=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],ot="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,or=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function oo(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function on(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function oi(e){return Uint8Array.from(e)}function os(e=32){let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}function oa(e,t=os){let{nonceLength:r}=e;r4(r);let o=(e,t)=>{let r=function(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];r8(o),t+=o.length}let r=new Uint8Array(t);for(let t=0,o=0;t<e.length;t++){let n=e[t];r.set(n,o),o+=n.length}return r}(e,t);return t.fill(0),r};return(n,...i)=>({encrypt(s){r8(s);let a=t(r),c=e(n,a,...i).encrypt(s);return c instanceof Promise?c.then(e=>o(a,e)):o(a,c)},decrypt(t){r8(t);let o=t.subarray(0,r),s=t.subarray(r);return e(n,o,...i).decrypt(s)}})}let oc=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),od=oc("expand 16-byte k"),ol=oc("expand 32-byte k"),ou=r9(od),op=r9(ol);function of(e,t){return e<<t|e>>>32-t}function oh(e){return e.byteOffset%4==0}let om=0x100000000-1,oy=Uint32Array.of();function og(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return r4(n),r4(s),r5(i),r5(r),(t,a,c,d,l=0)=>{let u,p;r8(t,void 0,"key"),r8(a,void 0,"nonce"),r8(c,void 0,"data");let f=c.length;if(void 0===d&&(d=new Uint8Array(f)),r8(d,void 0,"output"),r4(l),l<0||l>=om)throw Error("arx: counter overflow");if(d.length<f)throw Error(`arx: output (${d.length}) is shorter than data (${f})`);let h=[],m=t.length;if(32===m)h.push(u=oi(t)),p=op;else if(16===m&&r)(u=new Uint8Array(32)).set(t),u.set(t,16),p=ou,h.push(u);else throw r8(t,32,"arx key"),Error("invalid key size");oh(a)||h.push(a=oi(a));let y=r9(u);if(o){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");o(p,y,r9(a.subarray(0,16)),y),a=a.subarray(16)}let g=16-n;if(g!==a.length)throw Error(`arx: nonce must be ${g} or 16 bytes`);if(12!==g){let e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,h.push(a)}return!function(e,t,r,o,n,i,s,a){let c=n.length,d=new Uint8Array(64),l=r9(d),u=oh(n)&&oh(i),p=u?r9(n):oy,f=u?r9(i):oy;for(let h=0;h<c;s++){if(e(t,r,o,l,s,a),s>=om)throw Error("arx: counter overflow");let m=Math.min(64,c-h);if(u&&64===m){let e=h/4;
24if(h%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)f[r=e+t]=p[r]^l[t];h+=64;continue}for(let e=0,t;e<m;e++)i[t=h+e]=n[t]^d[e];h+=m}}(e,p,y,r9(a),c,d,l,s),r7(...h),d}}function ow(e,t){return 255&e[t++]|(255&e[t++])<<8}class ob{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){const t=ow(e=oi(r8(e,32,"key")),0),r=ow(e,2),o=ow(e,4),n=ow(e,6),i=ow(e,8),s=ow(e,10),a=ow(e,12),c=ow(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=ow(e,16+2*t)}process(e,t,r=!1){let{h:o,r:n}=this,i=n[0],s=n[1],a=n[2],c=n[3],d=n[4],l=n[5],u=n[6],p=n[7],f=n[8],h=n[9],m=ow(e,t+0),y=ow(e,t+2),g=ow(e,t+4),w=ow(e,t+6),b=ow(e,t+8),v=ow(e,t+10),E=ow(e,t+12),A=ow(e,t+14),x=o[0]+(8191&m),T=o[1]+((m>>>13|y<<3)&8191),k=o[2]+((y>>>10|g<<6)&8191),S=o[3]+((g>>>7|w<<9)&8191),_=o[4]+((w>>>4|b<<12)&8191),R=o[5]+(b>>>1&8191),U=o[6]+((b>>>14|v<<2)&8191),I=o[7]+((v>>>11|E<<5)&8191),O=o[8]+((E>>>8|A<<8)&8191),P=o[9]+(A>>>5|2048*!r),D=0,L=0+x*i+5*h*T+5*f*k+5*p*S+5*u*_;D=L>>>13,L&=8191,L+=5*l*R+5*d*U+5*c*I+5*a*O+5*s*P,D+=L>>>13,L&=8191;let Z=D+x*s+T*i+5*h*k+5*f*S+5*p*_;D=Z>>>13,Z&=8191,Z+=5*u*R+5*l*U+5*d*I+5*c*O+5*a*P,D+=Z>>>13,Z&=8191;let j=D+x*a+T*s+k*i+5*h*S+5*f*_;D=j>>>13,j&=8191,j+=5*p*R+5*u*U+5*l*I+5*d*O+5*c*P,D+=j>>>13,j&=8191;let C=D+x*c+T*a+k*s+S*i+5*h*_;D=C>>>13,C&=8191,C+=5*f*R+5*p*U+5*u*I+5*l*O+5*d*P,D+=C>>>13,C&=8191;let N=D+x*d+T*c+k*a+S*s+_*i;D=N>>>13,N&=8191,N+=5*h*R+5*f*U+5*p*I+5*u*O+5*l*P,D+=N>>>13,N&=8191;let $=D+x*l+T*d+k*c+S*a+_*s;D=$>>>13,$&=8191,$+=R*i+5*h*U+5*f*I+5*p*O+5*u*P,D+=$>>>13,$&=8191;let z=D+x*u+T*l+k*d+S*c+_*a;D=z>>>13,z&=8191,z+=R*s+U*i+5*h*I+5*f*O+5*p*P,D+=z>>>13,z&=8191;let H=D+x*p+T*u+k*l+S*d+_*c;D=H>>>13,H&=8191,H+=R*a+U*s+I*i+5*h*O+5*f*P,D+=H>>>13,H&=8191;let V=D+x*f+T*p+k*u+S*l+_*d;D=V>>>13,V&=8191,V+=R*c+U*a+I*s+O*i+5*h*P,D+=V>>>13,V&=8191;let q=D+x*h+T*f+k*p+S*u+_*l;D=q>>>13,q&=8191,q+=R*d+U*c+I*a+O*s+P*i,D+=q>>>13,q&=8191,L=8191&(D=(D=(D<<2)+D|0)+L|0),D>>>=13,Z+=D,o[0]=L,o[1]=Z,o[2]=j,o[3]=C,o[4]=N,o[5]=$,o[6]=z,o[7]=H,o[8]=V,o[9]=q}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=o,o=e[t]>>>13,e[t]&=8191;e[0]+=5*o,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+o,o=r[t]>>>13,r[t]&=8191;r[9]-=8192;let n=(1^o)-1;for(let e=0;e<10;e++)r[e]&=n;n=~n;for(let t=0;t<10;t++)e[t]=e[t]&n|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;r7(r)}update(e){r3(this),r8(e);let{buffer:t,blockLen:r}=this,o=(e=oi(e)).length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){r7(this.h,this.r,this.buffer,this.pad)}digestInto(e){r3(this);r8(e,void 0,"output");let t=this.outputLen;if(e.length<t)throw Error("digestInto() expects output buffer of length at least "+t);this.finished=!0;let{buffer:r,h:o}=this,{pos:n}=this;if(n){for(r[n++]=1;n<16;n++)r[n]=0;this.process(r,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=o[t]>>>0,e[i++]=o[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let ov=(c=e=>new ob(e),(i=(e,t)=>c(t).update(e).digest()).outputLen=(s=c(new Uint8Array(32))).outputLen,i.blockLen=s.blockLen,i.create=e=>c(e),i);function oE(e,t,r,o,n,i=20){let s=e[0],a=e[1],c=e[2],d=e[3],l=t[0],u=t[1],p=t[2],f=t[3],h=t[4],m=t[5],y=t[6],g=t[7],w=r[0],b=r[1],v=r[2],E=s,A=a,x=c,T=d,k=l,S=u,_=p,R=f,U=h,I=m,O=y,P=g,D=n,L=w,Z=b,j=v;for(let e=0;e<i;e+=2)U=U+(D=of(D^(E=E+k|0),16))|0,E=E+(k=of(k^U,12))|0,U=U+(D=of(D^E,8))|0,k=of(k^U,7),I=I+(L=of(L^(A=A+S|0),16))|0,A=A+(S=of(S^I,12))|0,I=I+(L=of(L^A,8))|0,S=of(S^I,7),O=O+(Z=of(Z^(x=x+_|0),16))|0,x=x+(_=of(_^O,12))|0,O=O+(Z=of(Z^x,8))|0,_=of(_^O,7),P=P+(j=of(j^(T=T+R|0),16))|0,T=T+(R=of(R^P,12))|0,P=P+(j=of(j^T,8))|0,R=of(R^P,7),O=O+(j=of(j^(E=E+S|0),16))|0,E=E+(S=of(S^O,12))|0,O=O+(j=of(j^E,8))|0,S=of(S^O,7),P=P+(D=of(D^(A=A+_|0),16))|0,A=A+(_=of(_^P,12))|0,P=P+(D=of(D^A,8))|0,_=of(_^P,7),U=U+(L=of(L^(x=x+R|0),16))|0,x=x+(R=of(R^U,12))|0,U=U+(L=of(L^x,8))|0,R=of(R^U,7),I=I+(Z=of(Z^(T=T+k|0),16))|0,T=T+(k=of(k^I,12))|0,I=I+(Z=of(Z^T,8))|0,k=of(k^I,7);let C=0;
24o[C++]=s+E|0,o[C++]=a+A|0,o[C++]=c+x|0,o[C++]=d+T|0,o[C++]=l+k|0,o[C++]=u+S|0,o[C++]=p+_|0,o[C++]=f+R|0,o[C++]=h+U|0,o[C++]=m+I|0,o[C++]=y+O|0,o[C++]=g+P|0,o[C++]=n+D|0,o[C++]=w+L|0,o[C++]=b+Z|0,o[C++]=v+j|0}let oA=og(oE,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ox=og(oE,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,o){let n=e[0],i=e[1],s=e[2],a=e[3],c=t[0],d=t[1],l=t[2],u=t[3],p=t[4],f=t[5],h=t[6],m=t[7],y=r[0],g=r[1],w=r[2],b=r[3];for(let e=0;e<20;e+=2)p=p+(y=of(y^(n=n+c|0),16))|0,n=n+(c=of(c^p,12))|0,p=p+(y=of(y^n,8))|0,c=of(c^p,7),f=f+(g=of(g^(i=i+d|0),16))|0,i=i+(d=of(d^f,12))|0,f=f+(g=of(g^i,8))|0,d=of(d^f,7),h=h+(w=of(w^(s=s+l|0),16))|0,s=s+(l=of(l^h,12))|0,h=h+(w=of(w^s,8))|0,l=of(l^h,7),m=m+(b=of(b^(a=a+u|0),16))|0,a=a+(u=of(u^m,12))|0,m=m+(b=of(b^a,8))|0,u=of(u^m,7),h=h+(b=of(b^(n=n+d|0),16))|0,n=n+(d=of(d^h,12))|0,h=h+(b=of(b^n,8))|0,d=of(d^h,7),m=m+(y=of(y^(i=i+l|0),16))|0,i=i+(l=of(l^m,12))|0,m=m+(y=of(y^i,8))|0,l=of(l^m,7),p=p+(g=of(g^(s=s+u|0),16))|0,s=s+(u=of(u^p,12))|0,p=p+(g=of(g^s,8))|0,u=of(u^p,7),f=f+(w=of(w^(a=a+c|0),16))|0,a=a+(c=of(c^f,12))|0,f=f+(w=of(w^a,8))|0,c=of(c^f,7);let v=0;o[v++]=n,o[v++]=i,o[v++]=s,o[v++]=a,o[v++]=y,o[v++]=g,o[v++]=w,o[v++]=b},allowShortKeys:!1}),oT=new Uint8Array(16),ok=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(oT.subarray(r))},oS=new Uint8Array(32);function o_(e,t,r,o,n){var i,s;let a,c;void 0!==n&&r8(n,void 0,"AAD");let d=e(t,r,oS),l=(i=o.length,s=n?n.length:0,r5(!0),(c=new DataView((a=new Uint8Array(16)).buffer,a.byteOffset,a.byteLength)).setBigUint64(0,BigInt(s),!0),c.setBigUint64(8,BigInt(i),!0),a),u=ov.create(d);n&&ok(u,n),ok(u,o),u.update(l);let p=u.digest();return r7(d,l),p}let oR=e=>(t,r,o)=>({encrypt(n,i){let s=n.length;(i=on(s+16,i,!1)).set(n);let a=i.subarray(0,-16);e(t,r,a,a,1);let c=o_(e,t,r,a,o);return i.set(c,s),r7(c),i},decrypt(n,i){i=on(n.length-16,i,!1);let s=n.subarray(0,-16),a=n.subarray(-16),c=o_(e,t,r,s,o);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return 0===r}(a,c))throw Error("invalid tag");return i.set(n.subarray(0,-16)),e(t,r,i,i,1),r7(c),i}});oR(oA);let oU=((e,t)=>{function r(o,...n){if(r8(o,void 0,"key"),!oe)throw Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&r8(n[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let i=e.tagLength;i&&void 0!==n[1]&&r8(n[1],void 0,"AAD");let s=t(o,...n),a=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");r8(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,r8(e),a(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(r8(e),i&&e.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16},oR(ox)),oI=new TextEncoder,oO=new TextDecoder;function oP(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let o of e)t.set(o,r),r+=o.length;return t}function oD(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:oO.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=oO.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{var r=t;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);let e=atob(r),o=new Uint8Array(e.length);for(let t=0;t<e.length;t++)o[t]=e.charCodeAt(t);return o}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function oL(e){let t=e;return("string"==typeof t&&(t=oI.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class oZ extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class oj extends oZ{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}
24),this.claim=r,this.reason=o,this.payload=t}}class oC extends oZ{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}),this.claim=r,this.reason=o,this.payload=t}}class oN extends oZ{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class o$ extends oZ{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class oz extends oZ{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class oH extends oZ{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class oV extends oZ{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class oq extends oZ{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class oB extends oZ{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class oK extends oZ{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let oM=(e,t)=>{let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};
24case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new o$(`alg ${e} is not supported either by JOSE or your javascript runtime`)}},oW=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function oF(e,t="algorithm.name"){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function oJ(e,t){return e.name===t}function oG(e){return parseInt(e.name.slice(4),10)}function oQ(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function oY(e,t,...r){return oQ(`Key for the ${e} algorithm must be `,t,...r)}let oX=async(e,t,r)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>oQ("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return!function(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!oJ(e.algorithm,"HMAC"))throw oF("HMAC");let r=parseInt(t.slice(2),10);if(oG(e.algorithm.hash)!==r)throw oF(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!oJ(e.algorithm,"RSASSA-PKCS1-v1_5"))throw oF("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(oG(e.algorithm.hash)!==r)throw oF(`SHA-${r}`,"algorithm.hash");break}
24case"PS256":case"PS384":case"PS512":{if(!oJ(e.algorithm,"RSA-PSS"))throw oF("RSA-PSS");let r=parseInt(t.slice(2),10);if(oG(e.algorithm.hash)!==r)throw oF(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!oJ(e.algorithm,"Ed25519"))throw oF("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!oJ(e.algorithm,t))throw oF(t);break;case"ES256":case"ES384":case"ES512":{if(!oJ(e.algorithm,"ECDSA"))throw oF("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw oF(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(t,e,r),t},o0=async(e,t,r)=>{let o=await oX(e,t,"sign");return oW(e,o),new Uint8Array(await crypto.subtle.sign(oM(e,o.algorithm),o,r))},o1=(...e)=>{let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0};function o2(e){return e?.[Symbol.toStringTag]==="CryptoKey"}function o6(e){return e?.[Symbol.toStringTag]==="KeyObject"}let o5=e=>o2(e)||o6(e),o4=e=>{if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function o8(e){return o4(e)&&"string"==typeof e.kty}let o3=e=>e?.[Symbol.toStringTag],o9=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let o;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):o=r;break;case e.startsWith("PBES2"):o="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):o=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):o="wrapKey";break;case"decrypt"===r:o=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(o&&t.key_ops?.includes?.(o)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}return!0},o7=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?((e,t,r)=>{if(!(t instanceof Uint8Array)){if(o8(t)){if("oct"===t.kty&&"string"==typeof t.k&&o9(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!o5(t))throw TypeError(oY(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${o3(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,r):((e,t,r)=>{if(o8(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&o9(e,t,r))return;throw TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&o9(e,t,r))return;throw TypeError("JSON Web Key for this operation be a public JWK")}if(!o5(t))throw TypeError(oY(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${o3(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${o3(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${o3(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${o3(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${o3(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,r)},ne=(e,t,r,o,n)=>{let i;if(void 0!==n.crit&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let s of(i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,o.crit)){if(!i.has(s))throw new o$(`Extension Header Parameter "${s}" is not recognized`);if(void 0===n[s])throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&void 0===o[s])throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)},nt=async e=>{if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new o$('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new o$('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 o$('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;
24case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new o$('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new o$('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),o={...e};return"AKP"!==o.kty&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)},nr=async(e,r,o,n=!1)=>{let i=(t||=new WeakMap).get(e);if(i?.[o])return i[o];let s=await nt({...r,alg:o});return n&&Object.freeze(e),i?i[o]=s:t.set(e,{[o]:s}),s},no=async(e,r)=>{if(e instanceof Uint8Array||o2(e))return e;if(o6(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,r)=>{let o,n=(t||=new WeakMap).get(e);if(n?.[r])return n[r];let i="public"===e.type,s=!!i;if("x25519"===e.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}o=e.toCryptoKey(e.asymmetricKeyType,s,i?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,s,[i?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==e.asymmetricKeyType.toUpperCase())throw TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,s,[i?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(r){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}if(r.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},s,i?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},s,[i?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===r&&"P-256"===t&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:t},s,[i?"verify":"sign"])),"ES384"===r&&"P-384"===t&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:t},s,[i?"verify":"sign"])),"ES512"===r&&"P-521"===t&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:t},s,[i?"verify":"sign"])),r.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:t},s,i?[]:["deriveBits"]))}if(!o)throw TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[r]=o:t.set(e,{[r]:o}),o})(e,r)}catch(e){if(e instanceof TypeError)throw e}let o=e.export({format:"jwk"});return nr(e,o,r)}if(o8(e))return e.k?oD(e.k):nr(e,e,r,!0);throw Error("unreachable")};class nn{#t;#r;#o;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#t=e}setProtectedHeader(e){if(this.#r)throw TypeError("setProtectedHeader can only be called once");return this.#r=e,this}setUnprotectedHeader(e){if(this.#o)throw TypeError("setUnprotectedHeader can only be called once");return this.#o=e,this}async sign(e,t){let r;if(!this.#r&&!this.#o)throw new oz("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!o1(this.#r,this.#o))throw new oz("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this.#r,...this.#o},n=ne(oz,new Map([["b64",!0]]),t?.crit,this.#r,o),i=!0;if(n.has("b64")&&"boolean"!=typeof(i=this.#r.b64))throw new oz('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if("string"!=typeof s||!s)throw new oz('JWS "alg" (Algorithm) Header Parameter missing or invalid');o7(s,e,"sign");let a=this.#t;i&&(a=oI.encode(oL(a)));
24let c=oP(r=this.#r?oI.encode(oL(JSON.stringify(this.#r))):oI.encode(""),oI.encode("."),a),d=await no(e,s),l={signature:oL(await o0(s,d,c)),payload:""};return i&&(l.payload=oO.decode(a)),this.#o&&(l.header=this.#o),this.#r&&(l.protected=oO.decode(r)),l}}class ni{#n;constructor(e){this.#n=new nn(e)}setProtectedHeader(e){return this.#n.setProtectedHeader(e),this}async sign(e,t){let r=await this.#n.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}let ns=e=>Math.floor(e.getTime()/1e3),na=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,nc=e=>{let t,r=na.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let o=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(o);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*o);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*o);break;case"day":case"days":case"d":t=Math.round(86400*o);break;case"week":case"weeks":case"w":t=Math.round(604800*o);break;default:t=Math.round(0x1e187e0*o)}return"-"===r[1]||"ago"===r[4]?-t:t};function nd(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let nl=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;class nu{#t;constructor(e){if(!o4(e))throw TypeError("JWT Claims Set MUST be an object");this.#t=structuredClone(e)}data(){return oI.encode(JSON.stringify(this.#t))}get iss(){return this.#t.iss}set iss(e){this.#t.iss=e}get sub(){return this.#t.sub}set sub(e){this.#t.sub=e}get aud(){return this.#t.aud}set aud(e){this.#t.aud=e}set jti(e){this.#t.jti=e}set nbf(e){"number"==typeof e?this.#t.nbf=nd("setNotBefore",e):e instanceof Date?this.#t.nbf=nd("setNotBefore",ns(e)):this.#t.nbf=ns(new Date)+nc(e)}set exp(e){"number"==typeof e?this.#t.exp=nd("setExpirationTime",e):e instanceof Date?this.#t.exp=nd("setExpirationTime",ns(e)):this.#t.exp=ns(new Date)+nc(e)}set iat(e){void 0===e?this.#t.iat=ns(new Date):e instanceof Date?this.#t.iat=nd("setIssuedAt",ns(e)):"string"==typeof e?this.#t.iat=nd("setIssuedAt",ns(new Date)+nc(e)):this.#t.iat=nd("setIssuedAt",e)}}class np{#r;#i;constructor(e={}){this.#i=new nu(e)}setIssuer(e){return this.#i.iss=e,this}setSubject(e){return this.#i.sub=e,this}setAudience(e){return this.#i.aud=e,this}setJti(e){return this.#i.jti=e,this}setNotBefore(e){return this.#i.nbf=e,this}setExpirationTime(e){return this.#i.exp=e,this}setIssuedAt(e){return this.#i.iat=e,this}setProtectedHeader(e){return this.#r=e,this}async sign(e,t){let r=new ni(this.#i.data());if(r.setProtectedHeader(this.#r),Array.isArray(this.#r?.crit)&&this.#r.crit.includes("b64")&&!1===this.#r.b64)throw new oH("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}let nf=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),nh=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),nm=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),ny=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),ng=BigInt(0x100000000-1),nw=BigInt(32),nb=function(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:r,l:s}=function(e,t=!1){return t?{h:Number(e&ng),l:Number(e>>nw&ng)}:{h:0|Number(e>>nw&ng),l:0|Number(e&ng)}}(e[i],t);[o[i],n[i]]=[r,s]}return[o,n]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b89
246f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),nv=nb[0],nE=nb[1],nA=new Uint32Array(80),nx=new Uint32Array(80);function nT(e){switch(e){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${e}`)}}function nk(...e){let t=e.map(nT).join("");if(0===t.length)throw Error("No valid characters provided for random string generation.");let r=t.length;return(e,...o)=>{let n;if(e<=0)throw Error("Length must be a positive integer.");let i=t,s=r;o.length>0&&(s=(i=o.map(nT).join("")).length);let a=Math.floor(256/s)*s,c=new Uint8Array(2*e),d=c.length,l="",u=d;for(;l.length<e;)u>=d&&(G(c),u=0),(n=c[u++])<a&&(l+=i[n%s]);return l}}let nS=nk("a-z","0-9","A-Z","-_");async function n_(e,t,r=3600){return await new np(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}let nR=async({key:e,data:t})=>{let r=await r6("SHA-256").digest(e),o=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var n=oa(oU)(new Uint8Array(r)).encrypt(o);if(r8(n),ot)return n.toHex();let i="";for(let e=0;e<n.length;e++)i+=or[n[e]];return i},nU=async({key:e,data:t})=>{let r=await r6("SHA-256").digest(e),o=function(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(ot)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let t=0,n=0;t<r;t++,n+=2){let r=oo(e.charCodeAt(n)),i=oo(e.charCodeAt(n+1));if(void 0===r||void 0===i)throw Error('hex string expected, got non-hex character "'+(e[n]+e[n+1])+'" at index '+n);o[t]=16*r+i}return o}(t),n=oa(oU)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(o))},nI=async(e,t,r,o)=>{let n=await oX(e,t,"verify");oW(e,n);let i=oM(e,n.algorithm);try{return await crypto.subtle.verify(i,n,r,o)}catch{return!1}};async function nO(e,t,r){let o,n;if(!o4(e))throw new oz("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new oz('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new oz("JWS Protected Header incorrect type");if(void 0===e.payload)throw new oz("JWS Payload missing");if("string"!=typeof e.signature)throw new oz("JWS Signature missing or incorrect type");if(void 0!==e.header&&!o4(e.header))throw new oz("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let t=oD(e.protected);i=JSON.parse(oO.decode(t))}
24catch{throw new oz("JWS Protected Header is invalid")}if(!o1(i,e.header))throw new oz("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...e.header},a=ne(oz,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&"boolean"!=typeof(c=i.b64))throw new oz('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:d}=s;if("string"!=typeof d||!d)throw new oz('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&((e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)})("algorithms",r.algorithms);if(l&&!l.has(d))throw new oN('"alg" (Algorithm) Header Parameter value not allowed');if(c){if("string"!=typeof e.payload)throw new oz("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new oz("JWS Payload must be a string or an Uint8Array instance");let u=!1;"function"==typeof t&&(t=await t(i,e),u=!0),o7(d,t,"verify");let p=oP(oI.encode(e.protected??""),oI.encode("."),"string"==typeof e.payload?oI.encode(e.payload):e.payload);try{o=oD(e.signature)}catch{throw new oz("Failed to base64url decode the signature")}let f=await no(t,d);if(!await nI(d,f,o,p))throw new oK;if(c)try{n=oD(e.payload)}catch{throw new oz("Failed to base64url decode the payload")}else n="string"==typeof e.payload?oI.encode(e.payload):e.payload;let h={payload:n};return(void 0!==e.protected&&(h.protectedHeader=i),void 0!==e.header&&(h.unprotectedHeader=e.header),u)?{...h,key:f}:h}async function nP(e,t,r){if(e instanceof Uint8Array&&(e=oO.decode(e)),"string"!=typeof e)throw new oz("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=e.split(".");if(3!==s)throw new oz("Invalid Compact JWS");let a=await nO({payload:n,protected:o,signature:i},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}async function nD(e,t,r){let o=await nP(e,t,r);if(o.protectedHeader.crit?.includes("b64")&&!1===o.protectedHeader.b64)throw new oH("JWTs MUST NOT use unencoded payload");let n={payload:function(e,t,r={}){var o,n;let i,s;try{i=JSON.parse(oO.decode(t))}catch{}if(!o4(i))throw new oH("JWT Claims Set must be a top-level JSON object");let{typ:a}=r;if(a&&("string"!=typeof e.typ||nl(e.typ)!==nl(a)))throw new oj('unexpected "typ" JWT header value',i,"typ","check_failed");let{requiredClaims:c=[],issuer:d,subject:l,audience:u,maxTokenAge:p}=r,f=[...c];for(let e of(void 0!==p&&f.push("iat"),void 0!==u&&f.push("aud"),void 0!==l&&f.push("sub"),void 0!==d&&f.push("iss"),new Set(f.reverse())))if(!(e in i))throw new oj(`missing required "${e}" claim`,i,e,"missing");if(d&&!(Array.isArray(d)?d:[d]).includes(i.iss))throw new oj('unexpected "iss" claim value',i,"iss","check_failed");if(l&&i.sub!==l)throw new oj('unexpected "sub" claim value',i,"sub","check_failed");if(u&&(o=i.aud,n="string"==typeof u?[u]:u,"string"==typeof o?!n.includes(o):!(Array.isArray(o)&&n.some(Set.prototype.has.bind(new Set(o))))))throw new oj('unexpected "aud" claim value',i,"aud","check_failed");switch(typeof r.clockTolerance){case"string":s=nc(r.clockTolerance);break;case"number":s=r.clockTolerance;break;case"undefined":s=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:h}=r,m=ns(h||new Date);if((void 0!==i.iat||p)&&"number"!=typeof i.iat)throw new oj('"iat" claim must be a number',i,"iat","invalid");if(void 0!==i.nbf){if("number"!=typeof i.nbf)throw new oj('"nbf" claim must be a number',i,"nbf","invalid");if(i.nbf>m+s)throw new oj('"nbf" claim timestamp check failed',i,"nbf","check_failed")}if(void 0!==i.exp){if("number"!=typeof i.exp)throw new oj('"exp" claim must be a number',i,"exp","invalid");if(i.exp<=m-s)throw new oC('"exp" claim timestamp check failed',i,"exp","check_failed")}if(p){let e=m-i.iat;if(e-s>("number"==typeof p?p:nc(p)))throw new oC('"iat" claim timestamp check failed (too far in the past)',i,"iat","check_failed");if(e<0-s)throw new oj('"iat" claim timestamp check failed (it should be in the past)',i,"iat","check_failed")}return i}(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return"function"==typeof t?{...n,key:o.key}:n}
24async function nL(e,t,r){let o;if(!o4(e))throw TypeError("JWK must be an object");switch(t??=e.alg,o??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return oD(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new o$('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return nt({...e,alg:t,ext:o});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return nt({...e,ext:o});case"EC":case"OKP":return nt({...e,alg:t,ext:o});default:throw new o$('Unsupported "kty" (Key Type) Parameter value')}}function nZ(e){return o4(e)}class nj{#s;#a=new WeakMap;constructor(e){if(!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(nZ)}(e))throw new oV("JSON Web Key Set malformed");this.#s=structuredClone(e)}jwks(){return this.#s}async getKey(e,t){let{alg:r,kid:o}={...e,...t?.header},n=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new o$('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this.#s.keys.filter(e=>{let t=n===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),t&&("string"==typeof e.alg||"AKP"===n)&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;
24case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:s,length:a}=i;if(0===a)throw new oq;if(1!==a){let e=new oB,t=this.#a;throw e[Symbol.asyncIterator]=async function*(){for(let e of i)try{yield await nC(t,e,r)}catch{}},e}return nC(this.#a,s,r)}}async function nC(e,t,r){let o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[r]){let e=await nL({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new oV("JSON Web Key Set members must be public keys");o[r]=e}return o[r]}"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(r="jose/v6.1.0");Symbol();Symbol();let nN=e=>nk("a-z","A-Z","0-9")(e||32);var ru=ru;let n$=W.object({id:W.string(),createdAt:W.date().default(()=>new Date),updatedAt:W.date().default(()=>new Date)});function nz(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.iterator in e)&&(!(Symbol.toStringTag in e)||"[object Module]"===Object.prototype.toString.call(e))}function nH(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,o=".",n){if(!nz(r))return e(t,{},o,n);let i=Object.assign({},r);for(let r in t){if("__proto__"===r||"constructor"===r)continue;let s=t[r];null!=s&&(n&&n(i,r,s,o)||(Array.isArray(s)&&Array.isArray(i[r])?i[r]=[...s,...i[r]]:nz(s)&&nz(i[r])?i[r]=e(s,i[r],(o?`${o}.`:"")+r.toString(),n):i[r]=s))}return i})(t,r,"",e),{})}function nV(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function nq(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function nB(e,t){if("string"!=typeof e&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if(("string"==typeof t||"boolean"==typeof t)&&(t={separator:t}),2==arguments.length&&!(void 0===t||"object"==typeof t&&null!==t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if("\\"===(t=t||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=function e(t,r=!0){if(Array.isArray(t)){let o=t.map(t=>`^${e(t,r)}$`);return`(?:${o.join("|")})`}let o="",n="",i=".";!0===r?(o="/",n="[/\\\\]",i="[^/\\\\]"):r&&((n=function(e){let t="";for(let r=0;r<e.length;r++)t+=nV(e[r]);return t}(o=r)).length>1?(n=`(?:${n})`,i=`((?!${n}).)`):i=`[^${n}]`);let s=r?`${n}+?`:"",a=r?`${n}*?`:"",c=r?t.split(o):[t],d="";for(let e=0;e<c.length;e++){let t=c[e],o=c[e+1],n="";if(t||!(e>0)){if(r&&(n=e===c.length-1?a:"**"!==o?s:""),r&&"**"===t){n&&(d+=0===e?"":n,d+=`(?:${i}*?${n})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(d+=nV(t[e+1]),e++):"?"===r?d+=i:"*"===r?d+=`${i}*?`:d+=nV(r)}d+=n}}return d}(e,t.separator),o=RegExp(`^${r}$`,t.flags),n=nq.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}n$.extend({providerId:W.string(),accountId:W.string(),userId:ru.string(),accessToken:W.string().nullish(),refreshToken:W.string().nullish(),idToken:W.string().nullish(),accessTokenExpiresAt:W.date().nullish(),refreshTokenExpiresAt:W.date().nullish(),scope:W.string().nullish(),password:W.string().nullish()}),n$.extend({email:W.string().transform(e=>e.toLowerCase()),emailVerified:W.boolean().default(!1),name:W.string(),image:W.string().nullish()}),n$.extend({userId:ru.string(),expiresAt:W.date(),token:W.string(),ipAddress:W.string().nullish(),userAgent:W.string().nullish()}),n$.extend({value:W.string(),expiresAt:W.date(),identifier:W.string()}),nH(),nH((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),nH((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0}),r$(async e=>{if(e.request?.method!=="POST"||!e.request)return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=t?.errorCallbackURL,c=t?.newUserCallbackURL,d=Array.isArray(o.options.trustedOrigins)?o.trustedOrigins:[...o.trustedOrigins,...await o.options.trustedOrigins?.(e.request)||[]],l=e.headers?.has("cookie"),u=(t,r)=>{if(t&&!d.some(e=>((e,t)=>{if(e.startsWith("/"))return!1;if(t.includes("*"))return t.includes("://")?nB(t)(rI(e)||e):nB(t)(rP(e));let r=rO(e);return"http:"!==r&&"https:"!==r&&r?e.startsWith(t):t===rI(e)})(t,e)||t?.startsWith("/")&&"origin"!==r&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(t)))throw e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config 25`,`Current list of trustedOrigins: ${d}`),new X("FORBIDDEN",{message:`Invalid ${r}`})};l&&!e.context.options.advanced?.disableCSRFCheck&&u(n,"origin"),i&&u(i,"callbackURL"),s&&u(s,"redirectURL"),a&&u(a,"errorCallbackURL"),c&&u(c,"newUserCallbackURL")});let nK=e=>r$(async t=>{if(!t.request)return;let{context:r}=t,o=e(t),n=Array.isArray(r.options.trustedOrigins)?r.trustedOrigins:[...r.trustedOrigins,...await r.options.trustedOrigins?.(t.request)||[]],i=(e,r)=>{if(e&&!n.some(t=>((e,t)=>{if(e.startsWith("/"))return!1;if(t.includes("*"))return t.includes("://")?nB(t)(rI(e)||e):nB(t)(rP(e));let r=rO(e);return"http:"!==r&&"https:"!==r&&r?e.startsWith(t):t===rI(e)})(e,t)||e?.startsWith("/")&&"origin"!==r&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(e)))throw t.context.logger.error(`Invalid ${r}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config 26`,`Current list of trustedOrigins: ${n}`),new X("FORBIDDEN",{message:`Invalid ${r}`})};for(let e of Array.isArray(o)?o:[o])i(e,"callbackURL")});async function nM(e,t,r,o=3600){return await n_({email:t.toLowerCase(),updateTo:r},e,o)}async function nW(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new X("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await nM(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expires
26In),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}rz("/send-verification-email",{method:"POST",body:W.object({email:W.email().meta({description:"The email to send the verification email to"}),callbackURL:W.string().meta({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=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new X("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await r0(e);if(!r){let r=await e.context.internalAdapter.findUserByEmail(t);return r&&await nW(e,r.user),e.json({status:!0})}if(r?.user.emailVerified)throw new X("BAD_REQUEST",{message:"You can only send a verification email to an unverified email"});if(r?.user.email!==t)throw new X("BAD_REQUEST",{message:"You can only send a verification email to your own email"});return await nW(e,r.user),e.json({status:!0})}),rz("/verify-email",{method:"GET",query:W.object({token:W.string().meta({description:"The token to verify the email"}),callbackURL:W.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[nK(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=>{let t;function r(t){if(e.query.callbackURL){if(e.query.callbackURL.includes("?"))throw e.redirect(`${e.query.callbackURL}&error=${t}`);throw e.redirect(`${e.query.callbackURL}?error=${t}`)}throw new X("UNAUTHORIZED",{message:t})}let{token:o}=e.query;try{t=await nD(o,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof oC)return r("token_expired");return r("invalid_token")}let n=W.object({email:W.string().email(),updateTo:W.string().optional()}).parse(t.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)return r("user_not_found");if(n.updateTo){let t=await r0(e);if(!t||t.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}let o=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1},e),i=await nM(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:o,url:`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${e.query.callbackURL||"/"}`,token:i},e.request),await rj(e,{session:t.session,user:{...t.user,email:n.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:{id:o.id,email:o.email,name:o.name,image:o.image,emailVerified:o.emailVerified,createdAt:o.createdAt,updatedAt:o.updatedAt}})}e.context.options.emailVerification?.onEmailVerification&&await e.context.options.emailVerification.onEmailVerification(i.user,e.request);
26let s=await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0},e);if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(s,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await r0(e);if(t&&t.user.email===n.email)await rj(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(i.user.id,e);if(!t)throw new X("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await rj(e,{session:t,user:{...i.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});let nF={isAction:!1};async function nJ(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw new X("BAD_REQUEST",{message:"callbackURL is required"});let o=nS(128),n=nS(32),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s},e);if(!a)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 X("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function nG(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r){e.context.logger.error("State Mismatch. Verification not found",{state:t});let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;throw e.redirect(`${r}?error=please_restart_the_process`)}let o=W.object({callbackURL:W.string(),codeVerifier:W.string(),errorURL:W.string().optional(),newUserURL:W.string().optional(),expiresAt:W.number(),link:W.object({email:W.string(),userId:ru.string()}).optional(),requestSignUp:W.boolean().optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now()){await e.context.internalAdapter.deleteVerificationValue(r.id);let t=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;throw e.redirect(`${t}?error=please_restart_the_process`)}return await e.context.internalAdapter.deleteVerificationValue(r.id),o}function nQ(e,t){return t.options.account?.encryptOAuthTokens&&e?nR({key:t.secret,data:e}):e}async function nY(e,{userInfo:t,account:r,callbackURL:o,disableSignUp:n,overrideUserInfo:i}){let s=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(t=>{r_.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;throw e.redirect(`${r}?error=internal_server_error`)}),a=s?.user,c=!a;if(s){let o=s.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(o){if(e.context.options.account?.updateAccountOnSignIn!==!1){let t=Object.fromEntries(Object.entries({idToken:r.idToken,accessToken:await nQ(r.accessToken,e.context),refreshToken:await nQ(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope}).filter(([e,t])=>void 0!==t));Object.keys(t).length>0&&await e.context.internalAdapter.updateAccount(o.id,t,e)}}else{let o=e.context.options.account?.accountLinking?.trustedProviders;if(!o?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return H&&r_.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:s.user.id,accessToken:await nQ(r.accessToken,e.context),refreshToken:await nQ(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope},e)}catch(e){return r_.error("Unable to link account",e),{error:"unable to link account",data:null}}}if(i){let{id:r,...o}=t;
26await e.context.internalAdapter.updateUser(s.user.id,{...o,email:t.email.toLowerCase(),emailVerified:t.email.toLowerCase()===s.user.email&&s.user.emailVerified||t.emailVerified})}}else{if(n)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:n,...i}=t;if(a=await e.context.internalAdapter.createOAuthUser({...i,email:t.email.toLowerCase()},{accessToken:await nQ(r.accessToken,e.context),refreshToken:await nQ(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()},e).then(e=>e?.user),!t.emailVerified&&a&&e.context.options.emailVerification?.sendOnSignUp){let t=await nM(e.context.secret,a.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:r,token:t},e.request)}}catch(e){if(r_.error(e),e instanceof X)return{error:e.message,data:null,isRegister:!1};return{error:"unable to create user",data:null,isRegister:!1}}}if(!a)return{error:"unable to create user",data:null,isRegister:!1};let d=await e.context.internalAdapter.createSession(a.id,e);return d?{data:{session:d,user:a},error:null,isRegister:c}:{error:"unable to create session",data:null,isRegister:!1}}let nX=W.enum(["apple","atlassian","cognito","discord","facebook","figma","github","microsoft","google","huggingface","slack","spotify","twitch","twitter","dropbox","kick","linear","linkedin","gitlab","tiktok","reddit","roblox","salesforce","vk","zoom","notion","kakao","naver","line","paypal"]).or(W.string());rz("/sign-in/social",{method:"POST",body:W.object({callbackURL:W.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:W.string().optional(),errorCallbackURL:W.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:nX,disableRedirect:W.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:W.optional(W.object({token:W.string().meta({description:"ID token from the provider"}),nonce:W.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:W.string().meta({description:"Access token from the provider"}).optional(),refreshToken:W.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:W.number().meta({description:"Expiry date of the token"}).optional()})),scopes:W.array(W.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:W.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:W.string().meta({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=>{let t=e.context.socialProviders.find(t=>t.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 X("NOT_FOUND",{message:rB});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new X("NOT_FOUND",{message:rM});let{token:r,nonce:o}=e.body.idToken;if(!await t.verifyIdToken(r,o))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new X("UNAUTHORIZED",{message:rK});let n=await t.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!n||!n?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new X("UNAUTHORIZED",{message:rW});if(!n.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new X("UNAUTHORIZED",{message:rF});let i=await nY(e,{userInfo:{...n.user,email:n.user.email,id:String(n.user.id),name:n.user.n
26ame||"",image:n.user.image,emailVerified:n.user.emailVerified||!1},account:{providerId:t.id,accountId:String(n.user.id),accessToken:e.body.idToken.accessToken},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp});if(i.error)throw new X("UNAUTHORIZED",{message:i.error});return await rj(e,i.data),e.json({redirect:!1,token:i.data.session.token,url:void 0,user:{id:i.data.user.id,email:i.data.user.email,name:i.data.user.name,image:i.data.user.image,emailVerified:i.data.user.emailVerified,createdAt:i.data.user.createdAt,updatedAt:i.data.user.updatedAt}})}let{codeVerifier:r,state:o}=await nJ(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`,scopes:e.body.scopes,loginHint:e.body.loginHint});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),rz("/sign-in/email",{method:"POST",body:W.object({email:W.string().meta({description:"Email of the user"}),password:W.string().meta({description:"Password of the user"}),callbackURL:W.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:W.boolean().meta({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=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new X("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!W.string().email().safeParse(t).success)throw new X("BAD_REQUEST",{message:"Invalid email"});let o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new X("UNAUTHORIZED",{message:rq});let n=o.accounts.find(e=>"credential"===e.providerId);if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new X("UNAUTHORIZED",{message:rq});let i=n?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new X("UNAUTHORIZED",{message:rq});if(!await e.context.password.verify({hash:i,password:r}))throw e.context.logger.error("Invalid password"),new X("UNAUTHORIZED",{message:rq});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new X("FORBIDDEN",{message:rJ});if(e.context.options?.emailVerification?.sendOnSignIn){let t=await nM(e.context.secret,o.user.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:o.user,url:r,token:t},e.request)}throw new X("FORBIDDEN",{message:rJ})}let s=await e.context.internalAdapter.createSession(o.user.id,e,!1===e.body.rememberMe);if(!s)throw e.context.logger.error("Failed to create session"),new X("UNAUTHORIZED",{message:"Failed to create session"});return await rj(e,{session:s,user:o.user},!1===e.body.rememberMe),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:{id:o.user.id,email:o.user.email,name:o.user.name,image:o.user.image,emailVerified:o.user.emailVerified,createdAt:o.user.createdAt,updatedAt:o.user.updatedAt}})});let n0=W.object({code:W.string().optional(),error:W.string().optional(),device_id:W.string().optional(),error_description:W.string().optional(),state:W.string().optional(),user:W.string().optional()});function n1(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>o.searchParams.set(e,t)),o.href}rz("/callback/:id",{method:["GET","POST"],body:n0.optional(),query:n0.optional(),metadata:nF},async e=>{let t,r,o,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{if("GET"===e.method)t=n0.parse(e.query);else if("POST"===e.method)t=n0.parse(e.body);else throw Error("Unsupported method")}catch(t){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",t),e.redirect(`${n}?error=invalid_callback_request`)}let{code:i,error:s,state:a,error_description:c,device_id:d}=t;if(s)throw e.redirect(`${n}?error=${s}&error_description=${c}`);if(!a)throw e.context.logger.error("State not found",s),e.redirect(`${n}?error=state_not_found`);let{codeVerifier:l,callbackURL:u,link:p,errorURL:f,newUserURL:h,requestSignUp:m}=await nG(e);function y(t){let r=f||n;throw r=r.includes("?")?`${r}&error=${t}`:`${r}?error=${t}`,e.redirect(r)}if(!i)throw e.context.logger.error("Code not found"),y("no_code");let g=e.context.socialProviders.find(t=>
26t.id===e.params.id);if(!g)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),y("oauth_provider_not_found");try{r=await g.validateAuthorizationCode({code:i,codeVerifier:l,deviceId:d,redirectURI:`${e.context.baseURL}/callback/${g.id}`})}catch(t){throw e.context.logger.error("",t),y("invalid_code")}let w=await g.getUserInfo({...r,user:e.body?.user?rR(e.body.user):void 0}).then(e=>e?.user);if(!w)return e.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!u)throw e.context.logger.error("No callback URL found"),y("no_callback_url");if(p){let t,o=e.context.options.account?.accountLinking?.trustedProviders;if(!o?.includes(g.id)&&!w.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),y("unable_to_link_account");if(w.email!==p.email&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return y("email_doesn't_match");let n=await e.context.internalAdapter.findAccount(String(w.id));if(n){if(n.userId.toString()!==p.userId.toString())return y("account_already_linked_to_different_user");let t=Object.fromEntries(Object.entries({accessToken:await nQ(r.accessToken,e.context),refreshToken:await nQ(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scopes?.join(",")}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(n.id,t)}else if(!await e.context.internalAdapter.createAccount({userId:p.userId,providerId:g.id,accountId:String(w.id),...r,accessToken:await nQ(r.accessToken,e.context),refreshToken:await nQ(r.refreshToken,e.context),scope:r.scopes?.join(",")},e))return y("unable_to_link_account");try{t=u.toString()}catch{t=u}throw e.redirect(t)}if(!w.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("email_not_found");let b=await nY(e,{userInfo:{...w,id:String(w.id),email:w.email,name:w.name||w.email},account:{providerId:g.id,accountId:String(w.id),...r,scope:r.scopes?.join(",")},callbackURL:u,disableSignUp:g.disableImplicitSignUp&&!m||g.options?.disableSignUp,overrideUserInfo:g.options?.overrideUserInfoOnSignIn});if(b.error)return e.context.logger.error(b.error.split(" ").join("_")),y(b.error.split(" ").join("_"));let{session:v,user:E}=b.data;await rj(e,{session:v,user:E});try{o=(b.isRegister&&h||u).toString()}catch{o=b.isRegister&&h||u}throw e.redirect(o)}),rz("/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=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw rC(e),new X("BAD_REQUEST",{message:rH});return await e.context.internalAdapter.deleteSession(t),rC(e),e.json({success:!0})}),rz("/request-password-reset",{method:"POST",body:W.object({email:W.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:W.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),new X("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let n=rp(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),i=nN(24);
26await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:n},e);let s=r?encodeURIComponent(r):"",a=`${e.context.baseURL}/reset-password/${i}?callbackURL=${s}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:i},e.request),e.json({status:!0})}),rz("/forget-password",{method:"POST",body:W.object({email:W.string().email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:W.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),new X("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let n=rp(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),i=nN(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:n},e);let s=r?encodeURIComponent(r):"",a=`${e.context.baseURL}/reset-password/${i}?callbackURL=${s}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:i},e.request),e.json({status:!0})}),rz("/reset-password/:token",{method:"GET",query:W.object({callbackURL:W.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[nK(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=>{var t,r;let o,{token:n}=e.params,{callbackURL:i}=e.query;if(!n||!i)throw e.redirect(n1(e.context,i,{error:"INVALID_TOKEN"}));let s=await e.context.internalAdapter.findVerificationValue(`reset-password:${n}`);if(!s||s.expiresAt<new Date)throw e.redirect(n1(e.context,i,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:n},o=new URL(i,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>o.searchParams.set(e,t)),o.href))}),rz("/reset-password",{method:"POST",query:W.object({token:W.string().optional()}).optional(),body:W.object({newPassword:W.string().meta({description:"The new password to set"}),token:W.string().meta({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=>{let t=e.body.token||e.query?.token;if(!t)throw new X("BAD_REQUEST",{message:rK});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new X("BAD_REQUEST",{message:rG});if(r.length>n)throw new X("BAD_REQUEST",{message:rQ});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new X("BAD_REQUEST",{message:rK});let a=s.value,c=await e.context.password.hash(r);if((await e.context.internalAdapter.findAccounts(a)).find(e=>"credential"===e.providerId)?await e.context.internalAdapter.updatePassword(a,c,e):await e.context.internalAdapter.createAccount({userId:a,providerId:"credential",password:c,accountId:a}
26,e),await e.context.internalAdapter.deleteVerificationValue(s.id),e.context.options.emailAndPassword?.onPasswordReset){let t=await e.context.internalAdapter.findUserById(a);t&&await e.context.options.emailAndPassword.onPasswordReset({user:t},e.request)}return e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteSessions(a),e.json({status:!0})}),rz("/change-password",{method:"POST",body:W.object({newPassword:W.string().meta({description:"The new password to set"}),currentPassword:W.string().meta({description:"The current password is required"}),revokeOtherSessions:W.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[r1],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=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new X("BAD_REQUEST",{message:rG});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new X("BAD_REQUEST",{message:rQ});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!a||!a.password)throw new X("BAD_REQUEST",{message:rY});let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new X("BAD_REQUEST",{message:rV});await e.context.internalAdapter.updateAccount(a.id,{password:c});let d=null;if(o){await e.context.internalAdapter.deleteSessions(n.user.id);let t=await e.context.internalAdapter.createSession(n.user.id,e);if(!t)throw new X("INTERNAL_SERVER_ERROR",{message:rH});await rj(e,{session:t,user:n.user}),d=t.token}return e.json({token:d,user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt}})}),rz("/set-password",{method:"POST",body:W.object({newPassword:W.string().meta({description:"The new password to set is required"})}),metadata:{SERVER_ONLY:!0},use:[r1]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new X("BAD_REQUEST",{message:rG});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new X("BAD_REQUEST",{message:rQ});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(e=>"credential"===e.providerId&&e.password),s=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:s},e),e.json({status:!0});throw new X("BAD_REQUEST",{message:"user already has a password"})}),rz("/delete-user",{method:"POST",use:[r1],body:W.object({callbackURL:W.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:W.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:W.string().meta({description:"The token to delete the user is required"}).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=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new X("NOT_FOUND");let t=e.context.session;
26if(e.body.password){let r=(await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!r||!r.password)throw new X("BAD_REQUEST",{message:rY});if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw new X("BAD_REQUEST",{message:rV})}if(e.body.token)return await n2({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=nS(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))},e);let o=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:o,token:r},e.request),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),o=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>1e3*o)throw new X("BAD_REQUEST",{message:"Session expired. Re-authenticate to perform this action."})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),rC(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})});let n2=rz("/delete-user/callback",{method:"GET",query:W.object({token:W.string().meta({description:"The token to verify the deletion request"}),callbackURL:W.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[nK(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new X("NOT_FOUND");let t=await r0(e);if(!t)throw new X("NOT_FOUND",{message:rW});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date||r.value!==t.user.id)throw new X("NOT_FOUND",{message:rK});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(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),rC(e);let n=e.context.options.user.deleteUser?.afterDelete;if(n&&await n(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})});rz("/change-email",{method:"POST",body:W.object({newEmail:W.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:W.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[r1],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"]}}}},422:{description:"Unprocessable Entity. Email already exists",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new X("BAD_REQUEST",{message:"Change email is disabled"});let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new X("BAD_REQUEST",{message:"Email is the same"});
26if(await e.context.internalAdapter.findUserByEmail(t))throw e.context.logger.error("Email already exists"),new X("BAD_REQUEST",{message:"Couldn't update your email"});if(!0!==e.context.session.user.emailVerified){if(await e.context.internalAdapter.findUserByEmail(t))throw new X("UNPROCESSABLE_ENTITY",{message:"User already exists. Use another email."});if(await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:t},e),await rj(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),e.context.options.emailVerification?.sendVerificationEmail){let r=await nM(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:{...e.context.session.user,email:t},url:o,token:r},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 X("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await nM(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:t,url:o,token:r},e.request),e.json({status:!0})}),rz("/error",{method:"GET",metadata:{...nF,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=>new Response(((e="Unknown")=>`<!DOCTYPE html> 27<html lang="en"> 28<head> 29 <meta charset="UTF-8"> 30 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 31 <title>Authentication Error</title> 32 <style> 33 :root { 34 --bg-color: #f8f9fa; 35 --text-color: #212529; 36 --accent-color: #000000; 37 --error-color: #dc3545; 38 --border-color: #e9ecef; 39 } 40 body { 41 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 42 background-color: var(--bg-color); 43 color: var(--text-color); 44 display: flex; 45 justify-content: center; 46 align-items: center; 47 height: 100vh; 48 margin: 0; 49 line-height: 1.5; 50 } 51 .error-container { 52 background-color: #ffffff; 53 border-radius: 12px; 54 box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05); 55 padding: 2.5rem; 56 text-align: center; 57 max-width: 90%; 58 width: 400px; 59 } 60 h1 { 61 color: var(--error-color); 62 font-size: 1.75rem; 63 margin-bottom: 1rem; 64 font-weight: 600; 65 } 66 p { 67 margin-bottom: 1.5rem; 68 color: #495057; 69 } 70 .btn { 71 background-color: var(--accent-color); 72 color: #ffffff; 73 text-decoration: none; 74 padding: 0.75rem 1.5rem; 75 border-radius: 6px; 76 transition: all 0.3s ease; 77 display: inline-block; 78 font-weight: 500; 79 border: 2px solid var(--accent-color); 80 } 81 .btn:hover { 82 background-color: #131721; 83 } 84 .error-code { 85 font-size: 0.875rem; 86 color: #6c757d; 87 margin-top: 1.5rem; 88 padding-top: 1.5rem; 89 border-top: 1px solid var(--border-color); 90 } 91 .icon { 92 font-size: 3rem; 93 margin-bottom: 1rem; 94 } 95 </style> 96</head> 97<body> 98 <div class="error-container"> 99 <div class="icon">\u26A0\uFE0F</div> 100 <h1>Better Auth Error</h1> 101 <p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p> 102 <a href="/" id="returnLink" class="btn">Return to Application</a> 103 <div class="error-code">Error Code: <span id="errorCode">${e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</span></div> 104 </div> 105</body> 106</html>`)(new URL(e.request?.url||"").searchParams.get("error")||"Unknown"),{headers:{"Content-Type":"text/html"}})),rz("/ok",{method:"GET",metadata:{...nF,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})),rz("/list-accounts",{method:"GET",use:[r1],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"},providerId:{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","providerId","createdAt","updatedAt","accountId","scopes"]}}}}}}}}},async e=>
106{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(e=>({id:e.id,providerId:e.providerId,createdAt:e.createdAt,updatedAt:e.updatedAt,accountId:e.accountId,scopes:e.scope?.split(",")||[]})))}),rz("/link-social",{method:"POST",requireHeaders:!0,body:W.object({callbackURL:W.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:nX,idToken:W.object({token:W.string(),nonce:W.string().optional(),accessToken:W.string().optional(),refreshToken:W.string().optional(),scopes:W.array(W.string()).optional()}).optional(),requestSignUp:W.boolean().optional(),scopes:W.array(W.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:W.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:W.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional()}),use:[r1],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"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=e.context.socialProviders.find(t=>t.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 X("NOT_FOUND",{message:rB});if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new X("NOT_FOUND",{message:rM});let{token:o,nonce:n}=e.body.idToken;if(!await r.verifyIdToken(o,n))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new X("UNAUTHORIZED",{message:rK});let i=await r.getUserInfo({idToken:o,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!i||!i?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new X("UNAUTHORIZED",{message:rW});let s=String(i.user.id);if(!i.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new X("UNAUTHORIZED",{message:rF});if((await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>e.providerId===r.id&&e.accountId===s))return e.json({url:"",status:!0,redirect:!1});let a=e.context.options.account?.accountLinking?.trustedProviders;if(!a?.includes(r.id)&&!i.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw new X("UNAUTHORIZED",{message:"Account not linked - linking not allowed"});if(i.user.email!==t.user.email&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw new X("UNAUTHORIZED",{message:"Account not linked - different emails not allowed"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,providerId:r.id,accountId:s,accessToken:e.body.idToken.accessToken,idToken:o,refreshToken:e.body.idToken.refreshToken,scope:e.body.idToken.scopes?.join(",")},e)}catch(e){throw new X("EXPECTATION_FAILED",{message:"Account not linked - unable to create account"})}if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{await e.context.internalAdapter.updateUser(t.user.id,{name:i.user?.name,image:i.user?.image})}catch(e){console.warn("Could not update user - "+e.toString())}return e.json({url:"",status:!0,redirect:!1})}let o=await nJ(e,{userId:t.user.id,email:t.user.email}),n=await r.createAuthorizationURL({state:o.state,codeVerifier:o.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`,scopes:e.body.scopes});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),rz("/unlink-account",{method:"POST",body:W.object({providerId:W.string(),accountId:W.string().optional()}),use:[r2],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{providerId:t,accountId:r}
106=e.body,o=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===o.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw new X("BAD_REQUEST",{message:"You can't unlink your last account"});let n=o.find(e=>r?e.accountId===r&&e.providerId===t:e.providerId===t);if(!n)throw new X("BAD_REQUEST",{message:"Account not found"});return await e.context.internalAdapter.deleteAccount(n.id),e.json({status:!0})});let n6=rz("/get-access-token",{method:"POST",body:W.object({providerId:W.string().meta({description:"The provider ID for the OAuth provider"}),accountId:W.string().meta({description:"The account ID associated with the refresh token"}).optional(),userId:W.string().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{providerId:t,accountId:r,userId:o}=e.body,n=e.request,i=await r0(e);if(n&&!i)throw e.error("UNAUTHORIZED");let s=i?.user?.id||o;if(!s)throw new X("BAD_REQUEST",{message:"Either userId or session is required"});if(!e.context.socialProviders.find(e=>e.id===t))throw new X("BAD_REQUEST",{message:`Provider ${t} is not supported.`});let a=(await e.context.internalAdapter.findAccounts(s)).find(e=>r?e.id===r&&e.providerId===t:e.providerId===t);if(!a)throw new X("BAD_REQUEST",{message:"Account not found"});let c=e.context.socialProviders.find(e=>e.id===t);if(!c)throw new X("BAD_REQUEST",{message:`Provider ${t} not found.`});try{var d,l;let t=null,r=a.accessTokenExpiresAt&&new Date(a.accessTokenExpiresAt).getTime()-Date.now()<5e3;a.refreshToken&&r&&c.refreshAccessToken&&(t=await c.refreshAccessToken(a.refreshToken),await e.context.internalAdapter.updateAccount(a.id,{accessToken:await nQ(t.accessToken,e.context),accessTokenExpiresAt:t.accessTokenExpiresAt,refreshToken:await nQ(t.refreshToken,e.context),refreshTokenExpiresAt:t.refreshTokenExpiresAt}));let o={accessToken:await (d=t?.accessToken??a.accessToken??"",l=e.context,!d?d:l.options.account?.encryptOAuthTokens?nU({key:l.secret,data:d}):d),accessTokenExpiresAt:t?.accessTokenExpiresAt??a.accessTokenExpiresAt??void 0,scopes:a.scope?.split(",")??[],idToken:t?.idToken??a.idToken??void 0};return e.json(o)}catch(e){throw new X("BAD_REQUEST",{message:"Failed to get a valid access token",cause:e})}});rz("/refresh-token",{method:"POST",body:W.object({providerId:W.string().meta({description:"The provider ID for the OAuth provider"}),accountId:W.string().meta({description:"The account ID associated with the refresh token"}).optional(),userId:W.string().meta({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=>{let{providerId:t,accountId:r,userId:o}=e.body,n=e.request,i=await r0(e);if(n&&!i)throw e.error("UNAUTHORIZED");let s=i?.user?.id||o;if(!s)throw new X("BAD_REQUEST",{message:"Either userId or session is required"});let a=(await e.context.internalAdapter.findAccounts(s)).find(e=>r?e.id===r&&e.providerId===t:e.providerId===t);if(!a)throw new X("BAD_REQUEST",{message:"Account not found"});let c=e.context.socialProviders.find(e=>e.id===t);if(!c)throw new X("BAD_REQUEST",{message:`Provider ${t} not found.`});if(!c.refreshAccessToken)throw new X("BAD_REQUEST",{message:`Provider ${t} does not support token refreshing.`});try{let t=await c.refreshAccessToken(a.refreshToken);
106return await e.context.internalAdapter.updateAccount(a.id,{accessToken:await nQ(t.accessToken,e.context),refreshToken:await nQ(t.refreshToken,e.context),accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}),e.json(t)}catch(e){throw new X("BAD_REQUEST",{message:"Failed to refresh access token",cause:e})}}),rz("/account-info",{method:"POST",use:[r1],metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},email:{type:"string"},image:{type:"string"},emailVerified:{type:"boolean"}},required:["id","emailVerified"]},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data"],additionalProperties:!1}}}}}}},body:W.object({accountId:W.string().meta({description:"The provider given account id for which to get the account info"})})},async e=>{let t=await e.context.internalAdapter.findAccount(e.body.accountId);if(!t||t.userId!==e.context.session.user.id)throw new X("BAD_REQUEST",{message:"Account not found"});let r=e.context.socialProviders.find(e=>e.id===t.providerId);if(!r)throw new X("INTERNAL_SERVER_ERROR",{message:`Provider account provider is ${t.providerId} but it is not configured`});let o=await n6({...e,body:{accountId:t.id,providerId:t.providerId},returnHeaders:!1});if(!o.accessToken)throw new X("BAD_REQUEST",{message:"Access token not found"});let n=await r.getUserInfo({...o,accessToken:o.accessToken});return e.json(n)}),nH((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};let n5=K({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]});n5.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),n5.newRole({user:[],session:[]});let n4=!1,n8={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*:/},n3=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,n9={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},n7=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/,ie={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&"undefined"!=typeof window&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};var it=e.i(884702);function ir(e){var t,r;let{pluginPathMethods:o,pluginsActions:n,pluginsAtoms:i,$fetch:s,$store:a,atomListeners:c}=(e=>{var t;let r,o="credentials"in Request.prototype,n=function(e,t,r){let o,n;if(e)return rU(e,t);let i=$.BETTER_AUTH_URL||$.NEXT_PUBLIC_BETTER_AUTH_URL||$.PUBLIC_BETTER_AUTH_URL||$.NUXT_PUBLIC_BETTER_AUTH_URL||$.NUXT_PUBLIC_AUTH_URL||("/"!==$.BASE_URL?$.BASE_URL:void 0);if(i)return rU(i,t);return o&&n?rU(`${n}://${o}`,t):"undefined"!=typeof window&&window.location?rU(window.location.origin,t):void 0}(e?.baseURL,e?.basePath),i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>void 0!==e)||[],s={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:a,onError:c,onRequest:d,onResponse:l,...u}=e?.fetchOptions||{},p=(t={baseURL:n,...o?{credentials:"include"}:{},method:"GET",jsonParser:e=>e?function(e,t={strict:!0}){return function(e,t={}){let{strict:r=!1,warnings:o=!1,reviver:n,parseDates:i=!0}=t;if("string"!=typeof e)return e;let s=e.trim();if('"'===s[0]&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let a=s.toLowerCase();if(a.length<=9&&a in n9)return n9[a];
106if(!n3.test(s)){if(r)throw SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(n8).some(([e,t])=>{let r=t.test(s);return r&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),r})&&r)throw Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(e,t)=>{if("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t){o&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(i&&"string"==typeof t){let e=function(e){let t=n7.exec(e);if(!t)return null;let[,r,o,n,i,s,a,c,d,l,u]=t,p=new Date(Date.UTC(parseInt(r,10),parseInt(o,10)-1,parseInt(n,10),parseInt(i,10),parseInt(s,10),parseInt(a,10),c?parseInt(c.padEnd(3,"0"),10):0));if(d){let e=(60*parseInt(l,10)+parseInt(u,10))*("+"===d?-1:1);p.setUTCMinutes(p.getUTCMinutes()+e)}return p instanceof Date&&!isNaN(p.getTime())?p:null}(t);if(e)return e}return n?n(e,t):t})}catch(t){if(r)throw t;return e}}(e,t)}(e,{strict:!1}):null,customFetchImpl:fetch,...u,plugins:[s,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[ie],...i]},async function(e,r){let o,n=A(E(E({},t),r),{plugins:[...(null==t?void 0:t.plugins)||[],(o=t||{},{id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(e,t){var r,n,i,s;let a=(null==(n=null==(r=o.plugins)?void 0:r.find(t=>{var r;return null!=(r=t.schema)&&!!r.config&&(e.startsWith(t.schema.config.baseURL||"")||e.startsWith(t.schema.config.prefix||""))}))?void 0:n.schema)||o.schema;if(a){let r=e;(null==(i=a.config)?void 0:i.prefix)&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,""),a.config.baseURL&&(e=e.replace(a.config.prefix,a.config.baseURL))),(null==(s=a.config)?void 0:s.baseURL)&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,""));let o=a.schema[r];if(o){let r=A(E({},t),{method:o.method,output:o.output});return(null==t?void 0:t.disableValidation)||(r=A(E({},r),{body:o.input?await L(o.input,null==t?void 0:t.body):null==t?void 0:t.body,params:o.params?await L(o.params,null==t?void 0:t.params):null==t?void 0:t.params,query:o.query?await L(o.query,null==t?void 0:t.query):null==t?void 0:t.query})),{url:e,options:r}}}return{url:e,options:t}}})]});if(null==t?void 0:t.catchAllError)try{return await j(e,n)}catch(e){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:e}}}return await j(e,n)}),{$sessionSignal:h,session:m}={session:((e,t,r,o)=>{let n=f({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>i(e)}),i=e=>{let i="function"==typeof o?o({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):o;r(t,{...i,query:{...i?.query,...e?.query},async onSuccess(e){n.set({data:e.data,error:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await i?.onSuccess?.(e)},async onError(e){let{request:t}=e,r="number"==typeof t.retry?t.retry:t.retry?.attempts,o=t.retryAttempt||0;r&&o<r||(n.set({error:e.error,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await i?.onError?.(e))},async onRequest(e){let t=n.get();n.set({isPending:null===t.data,data:t.data,error:null,isRefetching:!0,refetch:n.value.refetch}),await i?.onRequest?.(e)}}).catch(e=>{n.set({error:e,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch})})};e=Array.isArray(e)?e:[e];let s=!1;for(let t of e)t.subscribe(()=>{q||(s?i():V(n,()=>(setTimeout(()=>{i()},0),s=!0,()=>{n.off(),t.off()})))});return n})(r=f(!1),"/get-session",p,{method:"GET"}),$sessionSignal:r},y=e?.plugins||[],g={},w={$sessionSignal:h,session:m},b={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},v=[{signal:"$sessionSignal",matcher:e=>"/sign-out"===e||"/update-user"===e||e.startsWith("/sign-in")||e.startsWith("/sign-up")||"/delete-user"===e||"/verify-email"===e}];for(let e of y)e.getAtoms&&Object.assign(w,e.getAtoms?.(p)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&v.push(...e.atomListeners);let x={notify:e=>{w[e].set(!w[e].get())},listen:(e,t)=>{w[e].subscribe(t)},atoms:w};for(let t of y)t.getActions&&Object.assign(g,t.getActions?.(p,x,e));return{pluginsActions:g,pluginsAtoms:w,pluginPathMethods:b,atomListeners:v,$fetch:p,$store:x}})(e),d={};for(let[e,t]of Object.entries(i)){d[`use${(r=e).charAt(0).toUpperCase()+r.slice(1)}`]=()=>(function(e,t={}){let r=(0,it.useRef)(e.get()),{keys:o,deps:n=[e,o]}=t,i=(0,it.useCallback)(t=>{let n=e=>{r.current!==e&&(r.current=e,t())};if(n(e.value),o?.length){let t;return t=new Set(o).add(void 0),e.listen((e,r,o)=>{t.has(o)&&n(e,r,o)})}return e.listen(n)},n),s=()=>r.current;return(0,it.useSyncExternalStore)(i,s,s)})(t)}return t={...n,...d,$fetch:s,$store:a},function e(r=[]){return new Proxy(function(){},{get(o,n){var i;if("then"===n||"catch"===n||"finally"===n)return;let s=[...r,n],a=t;for(let e of s)if(a&&"object"==typeof a&&e in a)a=a[e];else{a=void 0;break}return"function"==typeof a?a:"object"==typeof(i=a)&&null!==i&&"get"in i&&"function"==typeof i.get&&"lc"in i&&"number"==typeof i.lc?a:e(s)},apply:async(e,t,n)=>{let a="/"+r.map(e=>e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).join("/"),d=n[0]||{},l=n[1]||{},{query:u,fetchOptions:p,...f}=d,h={...l,...p},m=function(e,t,r){let o=t[e],{fetchOptions:n,query:i,...s}=r||{};return o||(n?.method?n.method:s&&Object.keys(s).length>0?"POST":"GET")}(a,o,d);return await s(a,{...h,body:"GET"===m?void 0:{...f,...h?.body||{}},query:u||h?.query,method:m,async onSuccess(e){await h?.onSuccess?.(e);let t=c?.find(e=>e.matcher(a));if(!t)return;let r=i[t.signal];if(!r)return;let o=r.get();setTimeout(()=>{r.set(!o)},10)}})}})}()}function io(){return{...{},fetchOptions:{retry:0,customFetchImpl:function({minIntervalMs:e}){let t=new Map,r=0;return async(o,n)=>{let i,s;if(!e||!function(e,t){if("GET"!==((t?.method??(e instanceof Request?e.method:"GET"))?.toUpperCase?.()??"GET"))return!1;let r="string"==typeof e?e:e instanceof URL?e.toString():e.url;return new URL(r,window.location.origin).pathname.endsWith("/get-session")}(o,n))return fetch(o,n);
106let a=(i="string"==typeof o?o:o instanceof URL?o.toString():o.url,s=new URL(i,window.location.origin),`GET ${s.origin}${s.pathname}`),c=t.get(a);if(c)return c;let d=Date.now(),l=Math.max(0,r+e-d),u=(async()=>(l>0&&await new Promise(e=>setTimeout(e,l)),r=Date.now(),fetch(o,n)))().finally(()=>{t.delete(a)});return t.set(a,u),u}}({minIntervalMs:ii})}}}e.i(551956);let ii=Number(d.default.env.NEXT_PUBLIC_AUTH_GET_SESSION_MIN_INTERVAL_MS)||2e3,is=ir(io()),{useSession:ia,signIn:ic,signUp:id,signOut:il}=is;function iu(e){var t;let r,o;return ir({...io(),plugins:(o=[],(t=e).google_client_id&&"true"===t.google_one_tap_enabled&&o.push((r={clientId:t.google_client_id,autoSelect:!1,cancelOnTapOutside:!1,context:"signin",additionalOptions:{},promptOptions:{baseDelay:1e3,maxAttempts:1}},{id:"one-tap",getActions:(e,t)=>({oneTap:async(t,o)=>{if(n4)return void console.warn("A Google One Tap request is already in progress. Please wait.");n4=!0;try{if("undefined"==typeof window||!window.document)return void console.warn("Google One Tap is only available in browser environments");let{autoSelect:n,cancelOnTapOutside:i,context:s}=t??{},a=s??r.context??"signin";await new Promise(e=>{if(window.googleScriptInitialized)return void e();let t=document.createElement("script");t.src="https://accounts.google.com/gsi/client",t.async=!0,t.defer=!0,t.onload=()=>{window.googleScriptInitialized=!0,e()},document.head.appendChild(t)}),await new Promise((s,c)=>{let d=!1,l=r.promptOptions?.baseDelay??1e3,u=r.promptOptions?.maxAttempts??5;window.google?.accounts.id.initialize({client_id:r.clientId,callback:async r=>{d=!0;try{await e("/one-tap/callback",{method:"POST",body:{idToken:r.credential},...t?.fetchOptions,...o}),(!t?.fetchOptions&&!o||t?.callbackURL)&&(window.location.href=t?.callbackURL??"/"),s()}catch(e){console.error("Error during One Tap callback:",e),c(e)}}
106,auto_select:n,cancel_on_tap_outside:i,context:a,...r.additionalOptions});let p=e=>{d||window.google?.accounts.id.prompt(r=>{if(!d){if(r.isDismissedMoment&&r.isDismissedMoment())if(e<u){let t=Math.pow(2,e)*l;setTimeout(()=>p(e+1),t)}else t?.onPromptNotification?.(r);else if(r.isSkippedMoment&&r.isSkippedMoment())if(e<u){let t=Math.pow(2,e)*l;setTimeout(()=>p(e+1),t)}else t?.onPromptNotification?.(r)}})};p(0)})}catch(e){throw console.error("Error during Google One Tap flow:",e),e}finally{n4=!1}}}),getAtoms:e=>({})})),o)})}e.s(["authClient",0,is,"getAuthClient",()=>iu,"signIn",0,ic,"signOut",0,il,"signUp",0,id,"useSession",0,ia],400969)}]);
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.