UNPKG

diesel-core

Version:

Web framework built on Web Standards

4 lines (3 loc) 24.8 kB
var c=Object.create;var{getPrototypeOf:k,defineProperty:R,getOwnPropertyNames:u}=Object;var x=Object.prototype.hasOwnProperty;var i=(g,f,L)=>{L=g!=null?c(k(g)):{};let $=f||!g||!g.__esModule?R(L,"default",{value:g,enumerable:!0}):L;for(let A of u(g))if(!x.call($,A))R($,A,{get:()=>g[A],enumerable:!0});return $};var o=((g)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(g,{get:(f,L)=>(typeof require!=="undefined"?require:f)[L]}):g)(function(g){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});class Q{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class D{root;constructor(){this.root=new Q}insert(g,f){let L=this.root,$=g.split("/").filter(Boolean);if(g==="/"){L.isEndOfWord=!0,L.handler.push(f.handler),L.path=g,L.method.push(f.method);return}for(let A of $){let C=!1,E=A;if(A.startsWith(":"))C=!0,E=":";if(!L.children[E])L.children[E]=new Q;L=L.children[E],L.isDynamic=C,L.pattern=A}L.isEndOfWord=!0,L.path=g,L.method.push(f.method),L.handler.push(f.handler)}search(g,f){let L=this.root,$=g.split("/").filter(Boolean),A=$.length;for(let G of $){let v=G;if(!L.children[v])if(L.children[":"])L=L.children[":"];else return null;else L=L.children[v]}let C=L.path.split("/").filter(Boolean);if(A!==C.length)return null;let E=L.method.indexOf(f);if(E!==-1)return{path:L.path,handler:L.handler[E],isDynamic:L.isDynamic,pattern:L.pattern,method:L.method[E]};return null}}function W(g){switch(g.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function I(g,f,L){let $=null,A=null,C=null,E=null,G={};return{req:g,server:f,url:L,status:200,headers:new Headers,setHeader(v,S){return this.headers.set(v,S),this},removeHeader(v){return this.headers.delete(v),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!$)try{$=Object.fromEntries(this.url.searchParams)}catch(v){throw new Error("Failed to parse query parameters")}return $},get params(){if(!A&&this.req.routePattern)try{A=s(this.req.routePattern,this.url.pathname)}catch(v){throw new Error("Failed to extract route parameters")}return A??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!E)E=(async()=>{let v=await r(this.req);if(v.error)throw new Error(v.error);return Object.keys(v).length===0?null:v})();return E},set(v,S){return G[v]=S,this},get(v){return G[v]},text(v,S){if(S)this.status=S;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(v,{status:this.status,headers:this.headers})},send(v,S){if(S)this.status=S;let U=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),K;if(v instanceof Uint8Array)K="Uint8Array";else if(v instanceof ArrayBuffer)K="ArrayBuffer";else K=typeof v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",U.get(K)??"text/plain; charset=utf-8");let Z=K==="object"&&v!==null?JSON.stringify(v):v;return new Response(Z,{status:this.status,headers:this.headers})},json(v,S){if(S)this.status=S;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(v,{status:this.status,headers:this.headers})},file(v,S,U){if(U)this.status=U;let K=Bun.file(v);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",S??W(v));return new Response(K,{status:this.status,headers:this.headers})},async ejs(v,S={},U){if(U)this.status=U;let K;try{K=await import("ejs"),K=K.default||K}catch(Z){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let Z=await Bun.file(v).text(),z=K.render(Z,S),P=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(z,{status:this.status,headers:P})}catch(Z){return console.error("EJS Rendering Error:",Z),new Response("Error rendering template",{status:500})}},redirect(v,S){if(S)this.status=S;else this.status=302;return this.headers.set("Location",v),new Response(null,{status:this.status,headers:this.headers})},stream(v){let S=new Headers(this.headers),U=new ReadableStream({async start(K){await v(K),K.close()}});return new Response(U,{headers:S})},yieldStream(v){return new Response({async*[Symbol.asyncIterator](){yield*v()}},{headers:this.headers})},setCookie(v,S,U={}){let K=`${encodeURIComponent(v)}=${encodeURIComponent(S)}`;if(U.maxAge)K+=`; Max-Age=${U.maxAge}`;if(U.expires)K+=`; Expires=${U.expires.toUTCString()}`;if(U.path)K+=`; Path=${U.path}`;if(U.domain)K+=`; Domain=${U.domain}`;if(U.secure)K+="; Secure";if(U.httpOnly)K+="; HttpOnly";if(U.sameSite)K+=`; SameSite=${U.sameSite}`;return this.headers.append("Set-Cookie",K),this},get cookies(){if(!C){let v=this.req.headers.get("cookie");C=v?l(v):{}}return C}}}function l(g){return Object.fromEntries(g.split(";").map((f)=>{let[L,...$]=f.trim().split("=");return[L,decodeURIComponent($.join("="))]}))}function s(g,f){let L={},$=g.split("/"),[A]=f.split("?"),C=A.split("/");if($.length!==C.length)return null;for(let E=0;E<$.length;E++)if($[E].startsWith(":"))L[$[E].slice(1)]=C[E];return L}async function r(g){let f=g.headers.get("Content-Type");if(!f)return{};if(g.headers.get("Content-Length")==="0"||!g.body)return{};try{if(f.startsWith("application/json"))return await g.json();if(f.startsWith("application/x-www-form-urlencoded")){let $=await g.text();return Object.fromEntries(new URLSearchParams($))}if(f.startsWith("multipart/form-data")){let $=await g.formData(),A={};for(let[C,E]of $.entries())A[C]=E;return A}return{error:"Unknown request body type"}}catch($){return{error:"Invalid request body format"}}}async function F(g,f,L,$){let A=I(g,f,L),C=$.trie.search(L.pathname,g.method);g.routePattern=C?.path;try{if($.hooks.onRequest)await J("onRequest",$.hooks.onRequest,[g,L,f]);if($.hasMiddleware){let v=await p($,L.pathname,A,f);if(v)return v}if($.hasFilterEnabled){let v=g.routePattern??L.pathname,S=await d($,v,A,f);if(S)return S}if(!C)return await t($,A,L.pathname);if($.hooks.preHandler){let v=await J("preHandler",$.hooks.preHandler,[A,f]);if(v)return v}let E=C.handler(A),G=E instanceof Promise?await E:E;if($.hasOnSendHook){let v=await J("onSend",$.hooks.onSend,[A,G,f]);if(v)return v}if(G instanceof Response)return G;return B(500,"No response returned from handler.")}catch(E){return await J("onError",$.hooks.onError,[E,g,L,f])||B(500,"Internal Server Error")}}async function J(g,f,L){if(!f?.length)return;for(let $=0;$<f.length;$++){let A=f[$](...L),C=A instanceof Promise?await A:A;if(C&&g!=="onRequest")return C}}async function p(g,f,L,$){if(g.globalMiddlewares.length){let C=await H(g.globalMiddlewares,L,$);if(C)return C}let A=g.middlewares.get(f)||[];if(A.length){let C=await H(A,L,$);if(C)return C}return null}async function H(g,f,L){for(let $ of g){let A=await $(f,L);if(A)return A}return null}async function _(g,f,L){for(let $ of g){let A=await $(f,L);if(A)return A}}async function d(g,f,L,$){let A=await h(g,f,L,$),C=A instanceof Promise?await A:A;if(C)return C}async function h(g,f,L,$){if(f.endsWith("/"))f=f.slice(0,-1);if(!g.filters.has(f))if(g.filterFunction.length)for(let A of g.filterFunction){let C=await A(L,$);if(C)return C}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function J1(g,f,L,$){if(!g.filters.has(f))if(g.filterFunction.length)for(let A of g.filterFunction){let C=await A(L,$);if(C)return C}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function t(g,f,L){if(g.staticPath){let A=await a(g,L,f);if(A)return A;let C=g.trie.search("*",f.req.method);if(C?.handler)return await C.handler(f)}return g.routeNotFoundFunc(f)||B(404,`Route not found for ${L}`)}function B(g,f){return new Response(JSON.stringify({error:f}),{status:g,headers:{"Content-Type":"application/json"}})}async function a(g,f,L){if(!g.staticPath)return null;let $=`${g.staticPath}${f}`;if(await Bun.file($).exists()){let C=W($);return L.file($,C,200)}return null}function Y(g){if(typeof g!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(g))}function M(g,f){var L="",$=0,A=-1,C=0,E;for(var G=0;G<=g.length;++G){if(G<g.length)E=g.charCodeAt(G);else if(E===47)break;else E=47;if(E===47){if(A===G-1||C===1);else if(A!==G-1&&C===2){if(L.length<2||$!==2||L.charCodeAt(L.length-1)!==46||L.charCodeAt(L.length-2)!==46){if(L.length>2){var v=L.lastIndexOf("/");if(v!==L.length-1){if(v===-1)L="",$=0;else L=L.slice(0,v),$=L.length-1-L.lastIndexOf("/");A=G,C=0;continue}}else if(L.length===2||L.length===1){L="",$=0,A=G,C=0;continue}}if(f){if(L.length>0)L+="/..";else L="..";$=2}}else{if(L.length>0)L+="/"+g.slice(A+1,G);else L=g.slice(A+1,G);$=G-A-1}A=G,C=0}else if(E===46&&C!==-1)++C;else C=-1}return L}function e(g,f){var L=f.dir||f.root,$=f.base||(f.name||"")+(f.ext||"");if(!L)return $;if(L===f.root)return L+$;return L+g+$}function N(){var g="",f=!1,L;for(var $=arguments.length-1;$>=-1&&!f;$--){var A;if($>=0)A=arguments[$];else{if(L===void 0)L=process.cwd();A=L}if(Y(A),A.length===0)continue;g=A+"/"+g,f=A.charCodeAt(0)===47}if(g=M(g,!f),f)if(g.length>0)return"/"+g;else return"/";else if(g.length>0)return g;else return"."}function j(g){if(Y(g),g.length===0)return".";var f=g.charCodeAt(0)===47,L=g.charCodeAt(g.length-1)===47;if(g=M(g,!f),g.length===0&&!f)g=".";if(g.length>0&&L)g+="/";if(f)return"/"+g;return g}function g1(g){return Y(g),g.length>0&&g.charCodeAt(0)===47}function f1(){if(arguments.length===0)return".";var g;for(var f=0;f<arguments.length;++f){var L=arguments[f];if(Y(L),L.length>0)if(g===void 0)g=L;else g+="/"+L}if(g===void 0)return".";return j(g)}function L1(g,f){if(Y(g),Y(f),g===f)return"";if(g=N(g),f=N(f),g===f)return"";var L=1;for(;L<g.length;++L)if(g.charCodeAt(L)!==47)break;var $=g.length,A=$-L,C=1;for(;C<f.length;++C)if(f.charCodeAt(C)!==47)break;var E=f.length,G=E-C,v=A<G?A:G,S=-1,U=0;for(;U<=v;++U){if(U===v){if(G>v){if(f.charCodeAt(C+U)===47)return f.slice(C+U+1);else if(U===0)return f.slice(C+U)}else if(A>v){if(g.charCodeAt(L+U)===47)S=U;else if(U===0)S=0}break}var K=g.charCodeAt(L+U),Z=f.charCodeAt(C+U);if(K!==Z)break;else if(K===47)S=U}var z="";for(U=L+S+1;U<=$;++U)if(U===$||g.charCodeAt(U)===47)if(z.length===0)z+="..";else z+="/..";if(z.length>0)return z+f.slice(C+S);else{if(C+=S,f.charCodeAt(C)===47)++C;return f.slice(C)}}function $1(g){return g}function C1(g){if(Y(g),g.length===0)return".";var f=g.charCodeAt(0),L=f===47,$=-1,A=!0;for(var C=g.length-1;C>=1;--C)if(f=g.charCodeAt(C),f===47){if(!A){$=C;break}}else A=!1;if($===-1)return L?"/":".";if(L&&$===1)return"//";return g.slice(0,$)}function A1(g,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');Y(g);var L=0,$=-1,A=!0,C;if(f!==void 0&&f.length>0&&f.length<=g.length){if(f.length===g.length&&f===g)return"";var E=f.length-1,G=-1;for(C=g.length-1;C>=0;--C){var v=g.charCodeAt(C);if(v===47){if(!A){L=C+1;break}}else{if(G===-1)A=!1,G=C+1;if(E>=0)if(v===f.charCodeAt(E)){if(--E===-1)$=C}else E=-1,$=G}}if(L===$)$=G;else if($===-1)$=g.length;return g.slice(L,$)}else{for(C=g.length-1;C>=0;--C)if(g.charCodeAt(C)===47){if(!A){L=C+1;break}}else if($===-1)A=!1,$=C+1;if($===-1)return"";return g.slice(L,$)}}function E1(g){Y(g);var f=-1,L=0,$=-1,A=!0,C=0;for(var E=g.length-1;E>=0;--E){var G=g.charCodeAt(E);if(G===47){if(!A){L=E+1;break}continue}if($===-1)A=!1,$=E+1;if(G===46){if(f===-1)f=E;else if(C!==1)C=1}else if(f!==-1)C=-1}if(f===-1||$===-1||C===0||C===1&&f===$-1&&f===L+1)return"";return g.slice(f,$)}function v1(g){if(g===null||typeof g!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof g);return e("/",g)}function G1(g){Y(g);var f={root:"",dir:"",base:"",ext:"",name:""};if(g.length===0)return f;var L=g.charCodeAt(0),$=L===47,A;if($)f.root="/",A=1;else A=0;var C=-1,E=0,G=-1,v=!0,S=g.length-1,U=0;for(;S>=A;--S){if(L=g.charCodeAt(S),L===47){if(!v){E=S+1;break}continue}if(G===-1)v=!1,G=S+1;if(L===46){if(C===-1)C=S;else if(U!==1)U=1}else if(C!==-1)U=-1}if(C===-1||G===-1||U===0||U===1&&C===G-1&&C===E+1){if(G!==-1)if(E===0&&$)f.base=f.name=g.slice(1,G);else f.base=f.name=g.slice(E,G)}else{if(E===0&&$)f.name=g.slice(1,C),f.base=g.slice(1,G);else f.name=g.slice(E,C),f.base=g.slice(E,G);f.ext=g.slice(C,G)}if(E>0)f.dir=g.slice(0,E-1);else if($)f.dir="/";return f}var S1="/",U1=":",K1=((g)=>(g.posix=g,g))({resolve:N,normalize:j,isAbsolute:g1,join:f1,relative:L1,_makeLong:$1,dirname:C1,basename:A1,extname:E1,format:v1,parse:G1,sep:S1,delimiter:U1,win32:null,posix:null}),V=K1;var{default:b}=(()=>({}));var X={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},T=(g,f,L)=>{let $=X[g]||X.reset,A=L?.method?X.method[L.method]||X.reset:X.reset,C=L?.status?L.status>=500?X.error:L.status>=400?X.warn:X.info:X.reset;console.log(` ${$}[${g.toUpperCase()}]${X.reset} ${f} - ${A}${L?.method||""}${X.reset}`);let E={timestamp:new Date().toISOString(),...L,status:L?.status?`${C}${L.status}${X.reset}`:void 0,method:L?.method?`${A>$}${L.method}${X.reset}`:void 0};console.log(JSON.stringify(E,null,2)+` `)},q=(g)=>{let{app:f,logger:L,logLevel:$="info",onRequest:A,onSend:C,onError:E}=g||{};f?.addHooks("onRequest",(G,v)=>{G.startTime=Date.now(),L?.()??T($,"Incoming Request",{method:G.method,url:v.toString(),headers:{"user-agent":G.headers.get("user-agent"),"content-type":G.headers.get("content-type")}}),A?.(G,v)}),f?.addHooks("onSend",async(G)=>{let v=`${Date.now()-G.req.startTime}ms`;L?.()??T($,"Response Sent",{method:G.req.method,url:G.url.toString(),status:G.status,duration:v,reqId:G.get?.("requestId"),headers:{"content-type":G.headers.get("content-type")}});let S=await C?.(G);if(S instanceof Response)return S}),f?.addHooks("onError",async(G,v,S)=>{L?.()??T("error","Unhandled Error",{method:v.method,url:S.toString(),status:500,error:G.message});let U=await E?.(G,v,S);if(U instanceof Response)return U})},O=(g,f,L,$=0,A,C)=>{let E=X.method[f]||X.reset,G=$>=500?X.error:$>=400?X.warn:X.info,v=C?`[${C}] `:"",S=g==="<--"?`${g} ${E}${f}${X.reset} ${L} ${v}`:`${g} ${E}${f}${X.reset} ${L} ${G}${$}${X.reset} ${A??""} ${v}`;console.log(S)},X1=(g)=>{let f=Date.now()-g;return f<1000?`${f}ms`:`${Math.round(f/1000)}s`},y=(g)=>{let{app:f,log:L,onRequest:$,onSend:A,onError:C}=g;f.addHooks("onRequest",(E,G)=>{E.startTime=Date.now(),L?.()??O("<--",E.method,G.pathname),$?.(E,G)}),f.addHooks("onSend",async(E)=>{let{method:G,url:v}=E.req,S=new URL(v).pathname,U=E.get?.("requestId");L?.()??O("-->",G,S,E.status,X1(E.req.startTime),U);let K=await A?.(E);if(K instanceof Response)return K}),f.addHooks("onError",async(E,G,v)=>{L?.()??O(E.message,G.method,v.toString(),500);let S=await C?.(E,G,v);if(S instanceof Response)return S})};function w(g,f){if(!g)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(L)=>{try{let $=L.cookies?.accessToken??L.req?.headers?.get("Authorization");if(!$)return L.json({message:"Unauthorized",error:"No token provided"},401);if($.startsWith("Bearer "))$=$.slice(7);let A=g?.verify($,f);if(!A)return L.json({message:"Unauthorized",error:"Token could not be decoded"},401);L.set("user",A)}catch($){let A="Invalid token";if($.name==="TokenExpiredError")A="Token expired";else if($.name==="JsonWebTokenError")A="Malformed or tampered token";return L.json({message:"Unauthorized",error:A},401)}}}function m(g,f,L){if(!g)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!f)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async($)=>{try{let A=$.cookies?.accessToken??$.req?.headers?.get("Authorization");if(!A)return $.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=g?.verify(A,L);if(!C)return $.json({message:"Unauthorized",error:"Token could not be decoded"},401);let E=await f.findById(C._id).select("-password -refreshToken");if(!E)return $.json({message:"Unauthorized: User not found"},404);$.set("user",E);return}catch(A){let C="Invalid token";if(A.name==="TokenExpiredError")C="Token expired";else if(A.name==="JsonWebTokenError")C="Malformed or tampered token";return $.json({message:"Unauthorized",error:C},401)}}}class n{static instance;fecth;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;constructor({jwtSecret:g,baseApiUrl:f,enableFileRouting:L,idleTimeOut:$,prefixApiUrl:A}={}){if(!n.instance)n.instance=this;this.prefixApiUrl=A??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=$??10,this.enableFileRouter=L??!1,this.baseApiUrl=f||"",this.user_jwt_secret=g||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new D,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{}}static router(g){if(!this.instance)console.log("no instance"),this.instance=new n;return new Proxy(this.instance,{get(f,L,$){return(A,C)=>{let E=g+A;return f[L](E,C)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...g)=>{return this.FilterRoutes=g,this.setupFilter()},permitAll:()=>{for(let g of this?.FilterRoutes){if(g.endsWith("/"))g=g.slice(0,-1);this.filters.add(g)}return this.FilterRoutes=null,this.setupFilter()},authenticate:(g)=>{if(g?.length)for(let f of g)this.filterFunction.push(f)},authenticateJwt:(g)=>{this.filterFunction.push(w(g,this.user_jwt_secret))},authenticateJwtDB:(g,f)=>{this.filterFunction.push(m(g,f,this.user_jwt_secret))}}}redirect(g,f,L){return this.any(g,($)=>{let A=$.params,C=f;if(A)for(let G in A)C=C.replace(`:${G}`,A[G]);let E=$.url.search;if(E)C+=E;return $.redirect(C,L)}),this}serveStatic(g){return this.staticPath=g,this}static(g){return this.staticPath=g,this}staticHtml(g){return this.staticFiles={...this.staticFiles,...g},this}addHooks(g,f){if(typeof g!=="string")throw new Error("hookName must be a string");if(typeof f!=="function")throw new Error("callback must be a instance of function");switch(g){case"onRequest":this.hooks.onRequest?.push(f);break;case"preHandler":this.hooks.preHandler?.push(f);break;case"postHandler":this.hooks.postHandler?.push(f);break;case"onSend":this.hooks.onSend?.push(f);break;case"onError":this.hooks.onError?.push(f);break;case"onClose":this.hooks.onClose?.push(f);break;default:throw new Error(`Unknown hook type: ${g}`)}return this}compile(){if(this?.globalMiddlewares?.length>0)this.hasMiddleware=!0;for(let[g,f]of this?.middlewares?.entries())if(f.length>0){this.hasMiddleware=!0;break}if(this?.enableFileRouter){let g=process.cwd(),f=V.join(g,"src","routes");if(b?.existsSync(f))this.loadRoutes(f,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(g,f,L){let $=await import(g),A;if(L===".ts")A=V.basename(g,".ts");else if(L===".js")A=V.basename(g,".js");let C=f+"/"+A;if(C.endsWith("/index"))C=f;else if(C.endsWith("/api"))C=f;C=C.replace(/\[(.*?)\]/g,":$1");let E=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let G of E)if($[G]){let v=G.toLowerCase(),S=$[G];this[v](`${this.baseApiUrl}${C}`,S)}}async loadRoutes(g,f){let L=await b.promises.readdir(g);for(let $ of L){let A=V.join(g,$);if((await b.promises.stat(A)).isDirectory())await this.loadRoutes(A,f+"/"+$);else if($.endsWith(".ts"))await this.registerFileRoutes(A,f,".ts");else if($.endsWith(".js"))await this.registerFileRoutes(A,f,".js")}}useLogger(g){return y(g),this}useAdvancedLogger(g){return q(g),this}BunRoute(g,f,...L){if(!f||typeof f!=="string")throw new Error("give a path in string format");this.routes[f]=async($,A)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let E=await _(this.globalMiddlewares,$,A);if(E)return E}let C=this.middlewares.get(f)||[];if(C?.length){let E=await _(C,$,A);if(E)return E}}if(g!==$.method)return new Response("Method Not Allowed",{status:405});if(L.length===1){let C=L[0]($,A);if(C instanceof Promise)return await C??new Response("Not Found",{status:404});if(C instanceof Response)return C}else for(let C=0;C<L.length;C++){let E=L[C]($,A);if(E instanceof Promise)return await E??new Response("Not Found",{status:404});if(E instanceof Response)return E}}}listen(g,...f){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let L="0.0.0.0",$=void 0,A={};for(let E of f)if(typeof E==="string")L=E;else if(typeof E==="function")$=E;else if(typeof E==="object"&&E!==null)A=E;let C={port:g,hostname:L,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)C.routes=this.routes;if(A.cert&&A.key)C.certFile=A.cert,C.keyFile=A.key;if(this.serverInstance=Bun?.serve(C),$)$();return this.serverInstance}fetch(){return this.compile(),async(g,f)=>{let L=new URL(g.url);return F(g,f,L,this)}}close(g){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,g?g():console.log("Server has been stopped");else console.warn("Server is not running.")}route(g,f){g=g&&g.length>0?g:f?.prefixApiUrl;let L=f?.tempRoutes??new Map;for(let[$,A]of L.entries()){let C=$.replace(/::\w+$/,""),E=`${g}${C}`;if(!this.middlewares.has(E))this.middlewares.set(E,[]);A.handlers.slice(0,-1).forEach((U)=>{let K=this.middlewares.get(E);if(!K.includes(U))K.push(U)});let v=A.handlers[A.handlers.length-1],S=A.method;try{this.trie.insert(E,{handler:v,method:S})}catch(U){console.error(`Error inserting ${E}:`,U)}}return f=null,this}register(g,f){return this.route(g,f)}addRoute(g,f,L){if(typeof f!=="string")throw new Error(`Error in ${L[L.length-1]}: Path must be a string. Received: ${typeof f}`);if(typeof g!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof g}`);this.tempRoutes?.set(f+"::"+g,{method:g,handlers:L});let $=L.slice(0,-1),A=L[L.length-1];if(!this.middlewares.has(f))this.middlewares.set(f,[]);$.forEach((C)=>{if(f==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...$])];else if(!this.middlewares.get(f)?.includes(C))this.middlewares.get(f)?.push(C)});try{if(g==="ANY"){let C=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let E of C)this.trie.insert(f,{handler:A,method:E})}this.trie.insert(f,{handler:A,method:g})}catch(C){console.error(`Error inserting ${f}:`,C)}}use(g,f){if(Array.isArray(g))g.forEach(($)=>{if(typeof $==="function")this.globalMiddlewares.push($)});if(typeof g==="function"){if(this.globalMiddlewares.push(g),Array.isArray(f))f.forEach(($)=>{this.globalMiddlewares.push($)});return this}return(Array.isArray(g)?g.filter(($)=>typeof $==="string"):[g].filter(($)=>typeof $==="string")).forEach(($)=>{if(!this.middlewares.has($))this.middlewares.set($,[]);if(f)(Array.isArray(f)?f:[f]).forEach((C)=>{this.middlewares.get($)?.push(C)})}),this}get(g,...f){return this.addRoute("GET",g,f),this}post(g,...f){return this.addRoute("POST",g,f),this}put(g,...f){return this.addRoute("PUT",g,f),this}patch(g,...f){return this.addRoute("PATCH",g,f),this}delete(g,...f){return this.addRoute("DELETE",g,f),this}any(g,...f){return this.addRoute("ANY",g,f),this}head(g,...f){return this.addRoute("HEAD",g,f),this}options(g,...f){return this.addRoute("OPTIONS",g,f),this}propfind(g,...f){return this.addRoute("PROPFIND",g,f),this}routeNotFound(g){return this.routeNotFoundFunc=g,this}on(g,f,...L){let $=Array.isArray(g)?g:[g];for(let A of $){let C=A.toUpperCase();if(C.toLocaleLowerCase()in this)this[C.toLocaleLowerCase()](f,...L);else this.addRoute(C,f,L)}}}export{n as default};