manifest
Version:
Self-hosted Manifest LLM router with embedded server, SQLite database, and dashboard
2 lines (1 loc) • 28.5 kB
JavaScript
import{c as Te,r as we,o as Ie}from"./vendor-C-Y5oNOq.js";var Le={},ce={};const G=Object.create(null),q=e=>Le||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?G:globalThis),I=new Proxy(G,{get(e,t){return q()[t]??G[t]},has(e,t){return t in q()||t in G},set(e,t,n){const r=q(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;const n=q(!0);return delete n[t],!0},ownKeys(){const e=q(!0);return Object.keys(e)}});function y(e,t){return typeof process<"u"&&ce?ce[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}const j=1,g=4,N=8,S=24,le={eterm:g,cons25:g,console:g,cygwin:g,dtterm:g,gnome:g,hurd:g,jfbterm:g,konsole:g,kterm:g,mlterm:g,mosh:S,putty:g,st:g,"rxvt-unicode-24bit":S,terminator:S,"xterm-kitty":S},Ae=new Map(Object.entries({APPVEYOR:N,BUILDKITE:N,CIRCLECI:S,DRONE:N,GITEA_ACTIONS:S,GITHUB_ACTIONS:S,GITLAB_CI:N,TRAVIS:N})),Ue=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function Ne(){if(y("FORCE_COLOR")!==void 0)switch(y("FORCE_COLOR")){case"":case"1":case"true":return g;case"2":return N;case"3":return S;default:return j}if(y("NODE_DISABLE_COLORS")!==void 0&&y("NODE_DISABLE_COLORS")!==""||y("NO_COLOR")!==void 0&&y("NO_COLOR")!==""||y("TERM")==="dumb")return j;if(y("TMUX"))return S;if("TF_BUILD"in I&&"AGENT_NAME"in I)return g;if("CI"in I){for(const{0:e,1:t}of Ae)if(e in I)return t;return y("CI_NAME")==="codeship"?N:j}if("TEAMCITY_VERSION"in I)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(y("TEAMCITY_VERSION"))!==null?g:j;switch(y("TERM_PROGRAM")){case"iTerm.app":return!y("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(y("TERM_PROGRAM_VERSION"))!==null?N:S;case"HyperTerm":case"MacTerm":return S;case"Apple_Terminal":return N}if(y("COLORTERM")==="truecolor"||y("COLORTERM")==="24bit")return S;if(y("TERM")){if(/truecolor/.exec(y("TERM"))!==null)return S;if(/^xterm-256/.exec(y("TERM"))!==null)return N;const e=y("TERM").toLowerCase();if(le[e])return le[e];if(Ue.some(t=>t.exec(e)!==null))return g}return y("COLORTERM")?g:j}const P={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",fg:{red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m"}},se=["debug","info","success","warn","error"];function Pe(e,t){return se.indexOf(t)>=se.indexOf(e)}const Ce={info:P.fg.blue,success:P.fg.green,warn:P.fg.yellow,error:P.fg.red,debug:P.fg.magenta},De=(e,t,n)=>{const r=new Date().toISOString();return n?`${P.dim}${r}${P.reset} ${Ce[e]}${e.toUpperCase()}${P.reset} ${P.bright}[Better Auth]:${P.reset} ${t}`:`${r} ${e.toUpperCase()} [Better Auth]: ${t}`},Me=e=>{const t="warn",n=Ne()!==1,r=(s,o,i=[])=>{if(!Pe(t,s))return;const f=De(s,o,n);{s==="error"?console.error(f,...i):s==="warn"?console.warn(f,...i):console.log(f,...i);return}};return{...Object.fromEntries(se.map(s=>[s,(...[o,...i])=>r(s,o,i)])),get level(){return t}}};Me();function Fe(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{code:t,message:n,toString:()=>t}]))}Fe({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"});var J=class extends Error{constructor(e,t){super(e,t),this.name="BetterAuthError",this.message=e,this.stack=""}};function xe(e){try{return(new URL(e).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new J(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Be(e){try{const t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new J(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof J?t:new J(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function K(e,t="/api/auth"){if(Be(e),xe(e))return e;const n=e.replace(/\/+$/,"");return!t||t==="/"?n:(t=t.startsWith("/")?t:`/${t}`,`${n}${t}`)}function ke(e,t,n,r,s){if(e)return K(e,t);{const o=I.BETTER_AUTH_URL||I.NEXT_PUBLIC_BETTER_AUTH_URL||I.PUBLIC_BETTER_AUTH_URL||I.NUXT_PUBLIC_BETTER_AUTH_URL||I.NUXT_PUBLIC_AUTH_URL||(I.BASE_URL!=="/"?I.BASE_URL:void 0);if(o)return K(o,t)}if(typeof window<"u"&&window.location)return K(window.location.origin,t)}const Ve={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*:/},qe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,fe={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},je=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function $e(e){return e instanceof Date&&!isNaN(e.getTime())}function We(e){const t=je.exec(e);if(!t)return null;const[,n,r,s,o,i,f,a,c,u,d]=t,h=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(s,10),parseInt(o,10),parseInt(i,10),parseInt(f,10),a?parseInt(a.padEnd(3,"0"),10):0));if(c){const E=(parseInt(u,10)*60+parseInt(d,10))*(c==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+E)}return $e(h)?h:null}function He(e,t={}){const{strict:n=!1,warnings:r=!1,reviver:s,parseDates:o=!0}=t;if(typeof e!="string")return e;const i=e.trim();if(i.length>0&&i[0]==='"'&&i.endsWith('"')&&!i.slice(1,-1).includes('"'))return i.slice(1,-1);const f=i.toLowerCase();if(f.length<=9&&f in fe)return fe[f];if(!qe.test(i)){if(n)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Ve).some(([a,c])=>{const u=c.test(i);return u&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${a} pattern`),u})&&n)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(i,(c,u)=>{if(c==="__proto__"||c==="constructor"&&u&&typeof u=="object"&&"prototype"in u){r&&console.warn(`[better-json] Dropping "${c}" key to prevent prototype pollution`);return}if(o&&typeof u=="string"){const d=We(u);if(d)return d}return s?s(c,u):u})}catch(a){if(n)throw a;return e}}function Ge(e,t={strict:!0}){return He(e,t)}const Je={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};let L=[],F=0;const $=4,Oe=e=>{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(r){return n.lc=t.push(r),()=>{for(let o=F+$;o<L.length;)L[o]===r?L.splice(o,$):o+=$;let s=t.indexOf(r);~s&&(t.splice(s,1),--n.lc||n.off())}},notify(r,s){let o=!L.length;for(let i of t)L.push(i,n.value,r,s);if(o){for(F=0;F<L.length;F+=$)L[F](L[F+1],L[F+2],L[F+3]);L.length=0}},off(){},set(r){let s=n.value;s!==r&&(n.value=r,n.notify(s))},subscribe(r){let s=n.listen(r);return r(n.value),s},value:e};return n},Ye=5,W=6,H=10;let Xe=(e,t,n,r)=>(e.events=e.events||{},e.events[n+H]||(e.events[n+H]=r(s=>{e.events[n].reduceRight((o,i)=>(i(o),o),{shared:{},...s})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let s=e.events[n],o=s.indexOf(t);s.splice(o,1),s.length||(delete e.events[n],e.events[n+H](),delete e.events[n+H])}),Qe=1e3,Re=(e,t)=>Xe(e,r=>{let s=t(r);s&&e.events[W].push(s)},Ye,r=>{let s=e.listen;e.listen=(...i)=>(!e.lc&&!e.active&&(e.active=!0,r()),s(...i));let o=e.off;return e.events[W]=[],e.off=()=>{o(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let i of e.events[W])i();e.events[W]=[]}},Qe)},()=>{e.listen=s,e.off=o}});const Ke=()=>typeof window>"u",ze=(e,t,n,r)=>{const s=Oe({data:null,error:null,isPending:!0,isRefetching:!1,refetch:f=>o(f)}),o=async f=>new Promise(a=>{const c=typeof r=="function"?r({data:s.get().data,error:s.get().error,isPending:s.get().isPending}):r;n(t,{...c,query:{...c?.query,...f?.query},async onSuccess(u){s.set({data:u.data,error:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await c?.onSuccess?.(u)},async onError(u){const{request:d}=u,h=typeof d.retry=="number"?d.retry:d.retry?.attempts,E=d.retryAttempt||0;if(h&&E<h)return;const m=u.error.status===401;s.set({error:u.error,data:m?null:s.get().data,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await c?.onError?.(u)},async onRequest(u){const d=s.get();s.set({isPending:d.data===null,data:d.data,error:null,isRefetching:!0,refetch:s.value.refetch}),await c?.onRequest?.(u)}}).catch(u=>{s.set({error:u,data:s.get().data,isPending:!1,isRefetching:!1,refetch:s.value.refetch})}).finally(()=>{a(void 0)})});e=Array.isArray(e)?e:[e];let i=!1;for(const f of e)f.subscribe(async()=>{Ke()||(i?await o():Re(s,()=>{const a=setTimeout(async()=>{i||(await o(),i=!0)},0);return()=>{s.off(),f.off(),clearTimeout(a)}}))});return s},z=Symbol.for("better-auth:broadcast-channel"),Ze=()=>Math.floor(Date.now()/1e3);var et=class{listeners=new Set;name;constructor(e="better-auth.message"){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>"u"))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Ze()}))}catch{}}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return()=>{};const e=t=>{if(t.key!==this.name)return;const n=JSON.parse(t.newValue??"{}");n?.event!=="session"||!n?.data||this.listeners.forEach(r=>r(n))};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};function Z(e="better-auth.message"){return globalThis[z]||(globalThis[z]=new et(e)),globalThis[z]}const ee=Symbol.for("better-auth:focus-manager");var tt=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>"u"||typeof document>"u"||typeof window.addEventListener>"u")return()=>{};const e=()=>{document.visibilityState==="visible"&&this.setFocused(!0)};return document.addEventListener("visibilitychange",e,!1),()=>{document.removeEventListener("visibilitychange",e,!1)}}};function de(){return globalThis[ee]||(globalThis[ee]=new tt),globalThis[ee]}const te=Symbol.for("better-auth:online-manager");var nt=class{listeners=new Set;isOnline=typeof navigator<"u"?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return()=>{};const e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",t,!1),()=>{window.removeEventListener("online",e,!1),window.removeEventListener("offline",t,!1)}}};function ne(){return globalThis[te]||(globalThis[te]=new nt),globalThis[te]}const V=()=>Math.floor(Date.now()/1e3);function he(e){return typeof e=="object"&&e!==null&&"data"in e&&"error"in e?e:{data:e,error:null}}const rt=5;function st(e){const{sessionAtom:t,sessionSignal:n,$fetch:r,options:s={}}=e,o=s.sessionOptions?.refetchInterval??0,i=s.sessionOptions?.refetchOnWindowFocus??!0,f=s.sessionOptions?.refetchWhenOffline??!1,a={lastSync:0,lastSessionRequest:0,cachedSession:void 0},c=()=>f||ne().isOnline,u=O=>{if(!c())return;if(O?.event==="storage"){a.lastSync=V(),n.set(!n.get());return}const v=t.get(),_=()=>{a.lastSessionRequest=V(),r("/get-session").then(async l=>{let{data:p,error:x}=he(l);if(p?.needsRefresh)try{const k=await r("/get-session",{method:"POST"});({data:p,error:x}=he(k))}catch{}const X=p?.session&&p?.user?p:null;t.set({...v,data:X,error:x}),a.lastSync=V(),n.set(!n.get())}).catch(()=>{})};if(O?.event==="poll"){_();return}if(O?.event==="visibilitychange"){if(V()-a.lastSessionRequest<rt)return;a.lastSessionRequest=V()}if(O?.event==="visibilitychange"){_();return}(v?.data===null||v?.data===void 0)&&(a.lastSync=V(),n.set(!n.get()))},d=O=>{Z().post({event:"session",data:{trigger:O},clientId:Math.random().toString(36).substring(7)})},h=()=>{o&&o>0&&(a.pollInterval=setInterval(()=>{t.get()?.data&&u({event:"poll"})},o*1e3))},E=()=>{a.unsubscribeBroadcast=Z().subscribe(()=>{u({event:"storage"})})},m=()=>{i&&(a.unsubscribeFocus=de().subscribe(()=>{u({event:"visibilitychange"})}))},M=()=>{a.unsubscribeOnline=ne().subscribe(O=>{O&&u({event:"visibilitychange"})})};return{init:()=>{h(),E(),m(),M(),Z().setup(),de().setup(),ne().setup()},cleanup:()=>{a.pollInterval&&(clearInterval(a.pollInterval),a.pollInterval=void 0),a.unsubscribeBroadcast&&(a.unsubscribeBroadcast(),a.unsubscribeBroadcast=void 0),a.unsubscribeFocus&&(a.unsubscribeFocus(),a.unsubscribeFocus=void 0),a.unsubscribeOnline&&(a.unsubscribeOnline(),a.unsubscribeOnline=void 0),a.lastSync=0,a.lastSessionRequest=0,a.cachedSession=void 0},triggerRefetch:u,broadcastSessionUpdate:d}}function ot(e,t){const n=Oe(!1),r=ze(n,"/get-session",e,{method:"GET"});let s=()=>{};return Re(r,()=>{const o=st({sessionAtom:r,sessionSignal:n,$fetch:e,options:t});return o.init(),s=o.broadcastSessionUpdate,()=>{o.cleanup()}}),{session:r,$sessionSignal:n,broadcastSessionUpdate:o=>s(o)}}function re(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)==="[object Module]":!0}function oe(e,t,n=".",r){if(!re(t))return oe(e,{},n,r);const s={...t};for(const o of Object.keys(e)){if(o==="__proto__"||o==="constructor")continue;const i=e[o];i!=null&&(r&&r(s,o,i,n)||(Array.isArray(i)&&Array.isArray(s[o])?s[o]=[...i,...s[o]]:re(i)&&re(s[o])?s[o]=oe(i,s[o],(n?`${n}.`:"")+o.toString(),r):s[o]=i))}return s}function it(e){return(...t)=>t.reduce((n,r)=>oe(n,r,"",e),{})}const at=it();var ut=Object.defineProperty,ct=Object.defineProperties,lt=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertySymbols,ft=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable,_e=(e,t,n)=>t in e?ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A=(e,t)=>{for(var n in t||(t={}))ft.call(t,n)&&_e(e,n,t[n]);if(pe)for(var n of pe(t))dt.call(t,n)&&_e(e,n,t[n]);return e},U=(e,t)=>ct(e,lt(t)),ht=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},pt=async(e,t)=>{var n,r,s,o,i,f;let a=t||{};const c={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:a,hooks:c};for(const u of t?.plugins||[]){if(u.init){const d=await((n=u.init)==null?void 0:n.call(u,e.toString(),t));a=d.options||a,e=d.url}c.onRequest.push((r=u.hooks)==null?void 0:r.onRequest),c.onResponse.push((s=u.hooks)==null?void 0:s.onResponse),c.onSuccess.push((o=u.hooks)==null?void 0:o.onSuccess),c.onError.push((i=u.hooks)==null?void 0:i.onError),c.onRetry.push((f=u.hooks)==null?void 0:f.onRetry)}return{url:e,options:a,hooks:c}},ye=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}},_t=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function yt(e){if(typeof e=="number")return new ye({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new ye(e);case"exponential":return new _t(e);default:throw new Error("Invalid retry strategy")}}var gt=async e=>{const t={},n=async r=>typeof r=="function"?await r():r;if(e?.auth){if(e.auth.type==="Bearer"){const r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type==="Basic"){const[r,s]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!s)return t;t.authorization=`Basic ${btoa(`${r}:${s}`)}`}else if(e.auth.type==="Custom"){const[r,s]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!s)return t;t.authorization=`${r??""} ${s}`}}return t},Et=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ot(e){const t=e.headers.get("content-type"),n=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";const r=t.split(";").shift()||"";return Et.test(r)?"json":n.has(r)||r.startsWith("text/")?"text":"blob"}function Rt(e){try{return JSON.parse(e),!0}catch{return!1}}function ie(e){if(e===void 0)return!1;const t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function ge(e){try{return JSON.parse(e)}catch{return e}}function Ee(e){return typeof e=="function"}function mt(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Ee(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Ee(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function vt(e){const t=new Headers(e?.headers),n=await gt(e);for(const[r,s]of Object.entries(n||{}))t.set(r,s);if(!t.has("content-type")){const r=St(e?.body);r&&t.set("content-type",r)}return t}function St(e){return ie(e)?"application/json":null}function bt(e){if(!e?.body)return null;const t=new Headers(e?.headers);if(ie(e.body)&&!t.has("content-type")){for(const[n,r]of Object.entries(e?.body))r instanceof Date&&(e.body[n]=r.toISOString());return JSON.stringify(e.body)}return t.has("content-type")&&t.get("content-type")==="application/x-www-form-urlencoded"&&ie(e.body)?new URLSearchParams(e.body).toString():e.body}function Tt(e,t){var n;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){const r=(n=e.split("@")[1])==null?void 0:n.split("/")[0];return ve.includes(r)?r.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function wt(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var It=class me extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,me.prototype)}};async function Y(e,t){const n=await e["~standard"].validate(t);if(n.issues)throw new It(n.issues);return n.value}var ve=["get","post","put","patch","delete"],Lt=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,n){var r,s,o,i;const f=((s=(r=e.plugins)==null?void 0:r.find(a=>{var c;return(c=a.schema)!=null&&c.config?t.startsWith(a.schema.config.baseURL||"")||t.startsWith(a.schema.config.prefix||""):!1}))==null?void 0:s.schema)||e.schema;if(f){let a=t;(o=f.config)!=null&&o.prefix&&a.startsWith(f.config.prefix)&&(a=a.replace(f.config.prefix,""),f.config.baseURL&&(t=t.replace(f.config.prefix,f.config.baseURL))),(i=f.config)!=null&&i.baseURL&&a.startsWith(f.config.baseURL)&&(a=a.replace(f.config.baseURL,""));const c=f.schema[a];if(c){let u=U(A({},n),{method:c.method,output:c.output});return n?.disableValidation||(u=U(A({},u),{body:c.input?await Y(c.input,n?.body):n?.body,params:c.params?await Y(c.params,n?.params):n?.params,query:c.query?await Y(c.query,n?.query):n?.query})),{url:t,options:u}}}return{url:t,options:n}}}),At=e=>{async function t(n,r){const s=U(A(A({},e),r),{plugins:[...e?.plugins||[],Lt(e||{}),...r?.plugins||[]]});if(e?.catchAllError)try{return await ae(n,s)}catch(o){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:o}}}return await ae(n,s)}return t};function Ut(e,t){const{baseURL:n,params:r,query:s}=t||{query:{},params:{},baseURL:""};let o=e.startsWith("http")?e.split("/").slice(0,3).join("/"):n||"";if(e.startsWith("@")){const d=e.toString().split("@")[1].split("/")[0];ve.includes(d)&&(e=e.replace(`@${d}/`,"/"))}o.endsWith("/")||(o+="/");let[i,f]=e.replace(o,"").split("?");const a=new URLSearchParams(f);for(const[d,h]of Object.entries(s||{})){if(h==null)continue;let E;if(typeof h=="string")E=h;else if(Array.isArray(h)){for(const m of h)a.append(d,m);continue}else E=JSON.stringify(h);a.set(d,E)}if(r)if(Array.isArray(r)){const d=i.split("/").filter(h=>h.startsWith(":"));for(const[h,E]of d.entries()){const m=r[h];i=i.replace(E,m)}}else for(const[d,h]of Object.entries(r))i=i.replace(`:${d}`,String(h));i=i.split("/").map(encodeURIComponent).join("/"),i.startsWith("/")&&(i=i.slice(1));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",o.startsWith("http")?new URL(`${i}${c}`,o):`${o}${i}${c}`}var ae=async(e,t)=>{var n,r,s,o,i,f,a,c;const{hooks:u,url:d,options:h}=await pt(e,t),E=mt(h),m=new AbortController,M=(n=h.signal)!=null?n:m.signal,b=Ut(d,h),T=bt(h),O=await vt(h),v=Tt(d,h);let _=U(A({},h),{url:b,headers:O,body:T,method:v,signal:M});for(const w of u.onRequest)if(w){const R=await w(_);typeof R=="object"&&R!==null&&(_=R)}("pipeTo"in _&&typeof _.pipeTo=="function"||typeof((r=t?.body)==null?void 0:r.pipe)=="function")&&("duplex"in _||(_.duplex="half"));const{clearTimeout:l}=wt(h,m);let p=await E(_.url,_);l();const x={response:p,request:_};for(const w of u.onResponse)if(w){const R=await w(U(A({},x),{response:(s=t?.hookOptions)!=null&&s.cloneResponse?p.clone():p}));R instanceof Response?p=R:typeof R=="object"&&R!==null&&(p=R.response)}if(p.ok){if(!(_.method!=="HEAD"))return{data:"",error:null};const R=Ot(p),C={data:null,response:p,request:_};if(R==="json"||R==="text"){const D=await p.text(),be=(o=_.jsonParser)!=null?o:ge;C.data=await be(D)}else C.data=await p[R]();_?.output&&_.output&&!_.disableValidation&&(C.data=await Y(_.output,C.data));for(const D of u.onSuccess)D&&await D(U(A({},C),{response:(i=t?.hookOptions)!=null&&i.cloneResponse?p.clone():p}));return t?.throw?C.data:{data:C.data,error:null}}const X=(f=t?.jsonParser)!=null?f:ge,k=await p.text(),ue=Rt(k),Q=ue?await X(k):null,Se={response:p,responseText:k,request:_,error:U(A({},Q),{status:p.status,statusText:p.statusText})};for(const w of u.onError)w&&await w(U(A({},Se),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?p.clone():p}));if(t?.retry){const w=yt(t.retry),R=(c=t.retryAttempt)!=null?c:0;if(await w.shouldAttemptRetry(R,p)){for(const D of u.onRetry)D&&await D(x);const C=w.getDelay(R);return await new Promise(D=>setTimeout(D,C)),await ae(e,U(A({},t),{retryAttempt:R+1}))}}if(t?.throw)throw new ht(p.status,p.statusText,ue?Q:k);return{data:null,error:U(A({},Q),{status:p.status,statusText:p.statusText})}},B={};const Nt=e=>{if(typeof process>"u")return;const t=e??"/api/auth";if(B.NEXT_PUBLIC_AUTH_URL)return B.NEXT_PUBLIC_AUTH_URL;if(typeof window>"u"){if(B.NEXTAUTH_URL)try{return B.NEXTAUTH_URL}catch{}if(B.VERCEL_URL)try{const n=B.VERCEL_URL.startsWith("http")?"":"https://";return`${new URL(`${n}${B.VERCEL_URL}`).origin}${t}`}catch{}}},Pt=(e,t)=>{const n="credentials"in Request.prototype,r=ke(e?.baseURL,e?.basePath)??Nt(e?.basePath)??"/api/auth",s=e?.plugins?.flatMap(l=>l.fetchPlugins).filter(l=>l!==void 0)||[],o={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:i,onError:f,onRequest:a,onResponse:c,...u}=e?.fetchOptions||{},d=At({baseURL:r,...n?{credentials:"include"}:{},method:"GET",jsonParser(l){return l?Ge(l,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[o,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Je],...s]}),{$sessionSignal:h,session:E,broadcastSessionUpdate:m}=ot(d,e),M=e?.plugins||[];let b={};const T={$sessionSignal:h,session:E},O={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},v=[{signal:"$sessionSignal",matcher(l){return l==="/sign-out"||l==="/update-user"||l==="/update-session"||l==="/sign-up/email"||l==="/sign-in/email"||l==="/delete-user"||l==="/verify-email"||l==="/revoke-sessions"||l==="/revoke-session"||l==="/change-email"},callback(l){l==="/sign-out"?m("signout"):(l==="/update-user"||l==="/update-session")&&m("updateUser")}}];for(const l of M)l.getAtoms&&Object.assign(T,l.getAtoms?.(d)),l.pathMethods&&Object.assign(O,l.pathMethods),l.atomListeners&&v.push(...l.atomListeners);const _={notify:l=>{T[l].set(!T[l].get())},listen:(l,p)=>{T[l].subscribe(p)},atoms:T};for(const l of M)l.getActions&&(b=at(l.getActions?.(d,_,e)??{},b));return{get baseURL(){return r},pluginsActions:b,pluginsAtoms:T,pluginPathMethods:O,atomListeners:v,$fetch:d,$store:_}};function Ct(e){return typeof e=="object"&&e!==null&&"get"in e&&typeof e.get=="function"&&"lc"in e&&typeof e.lc=="number"}function Dt(e,t,n){const r=t[e],{fetchOptions:s,query:o,...i}=n||{};return r||(s?.method?s.method:i&&Object.keys(i).length>0?"POST":"GET")}function Mt(e,t,n,r,s){function o(i=[]){return new Proxy(function(){},{get(f,a){if(typeof a!="string"||a==="then"||a==="catch"||a==="finally")return;const c=[...i,a];let u=e;for(const d of c)if(u&&typeof u=="object"&&d in u)u=u[d];else{u=void 0;break}return typeof u=="function"||Ct(u)?u:o(c)},apply:async(f,a,c)=>{const u="/"+i.map(O=>O.replace(/[A-Z]/g,v=>`-${v.toLowerCase()}`)).join("/"),d=c[0]||{},h=c[1]||{},{query:E,fetchOptions:m,...M}=d,b={...h,...m},T=Dt(u,n,d);return await t(u,{...b,body:T==="GET"?void 0:{...M,...b?.body||{}},query:E||b?.query,method:T,async onSuccess(O){if(await b?.onSuccess?.(O),!s||b.disableSignal)return;const v=s.filter(l=>l.matcher(u));if(!v.length)return;const _=new Set;for(const l of v){const p=r[l.signal];if(!p)return;if(_.has(l.signal))continue;_.add(l.signal);const x=p.get();setTimeout(()=>{p.set(!x)},10),l.callback?.(u)}}})}})}return o()}function Ft(e){const t=e.listen(()=>{}),[n,r]=Te({value:e.get()}),s=e.subscribe(o=>{r("value",we(o))});return Ie(()=>s()),t(),()=>n.value}function xt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Bt(e){return`use${xt(e)}`}function Vt(e){const{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:s,atomListeners:o}=Pt(e),i={};for(const[f,a]of Object.entries(r))i[Bt(f)]=()=>Ft(a);return Mt({...n,...i},s,t,r,o)}export{Vt as c};