diesel-core 2.0.5 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.d.ts CHANGED
@@ -70,9 +70,10 @@ export default class Diesel {
70
70
  /**
71
71
  * Mount method
72
72
  * we can use 3rd party framework with diesel.js
73
- * or we can use it for sub routing also , even i recommend using mount or sub for sub routing
73
+ * for diesel , i recommend sub method
74
74
  */
75
- mount(prefix: string, instance: Diesel | DieselFetchHandler): void;
75
+ mount(prefix: string, instance: DieselFetchHandler | any): void;
76
+ sub(prefix: string, child: Diesel): void;
76
77
  /**
77
78
  * Registers a router instance for subrouting.
78
79
  * Allows defining subroutes like:
@@ -83,7 +84,6 @@ export default class Diesel {
83
84
  /**
84
85
  same as Route
85
86
  */
86
- sub(prefix: string, router: Diesel): void;
87
87
  private addMiddlewareInRouter;
88
88
  private addRoute;
89
89
  /**
package/dist/main.js CHANGED
@@ -1,12 +1,12 @@
1
- function J($){switch($.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"}}var x=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],S=Object.freeze({}),A="ALL";class B{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=S;urlObject=null;constructor($,L,z,Z,X,G){this.req=$,this.server=L,this.path=z,this.param=Z,this.env=X,this.executionContext=G,this.headers=null}setHeader($,L){if(!this.headers)this.headers=new Headers;return this.headers.set($,L),this}removeHeader($){if(this.headers)this.headers.delete($);return this}set($,L){if(this.contextData===S)this.contextData={};return this.contextData[$]=L,this}get($){if(this.contextData===S)return;return this.contextData[$]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):S;return this.parsedQuery}get params(){return this.param?this.param:S}get body(){if(this.req.method==="GET")return Promise.resolve(S);if(!this.parsedBody)this.parsedBody=(async()=>{try{let $=await a(this.req);if($.error)throw Error($.error);return Object.keys($).length===0?null:$}catch($){throw Error("Invalid request body format")}})();return this.parsedBody}text($,L=200,z){if(!this.headers){if(!z)return new Response($,{status:L,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Z={"Content-Type":"text/plain; charset=utf-8"};return I(z,Z),new Response($,{status:L,headers:Z})}if(z)_(this.headers,z);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response($,{status:L,headers:this.headers})}send($,L=200,z){let Z,X;if($ instanceof Uint8Array||$ instanceof ArrayBuffer)Z="application/octet-stream",X=$;else if($!==null&&typeof $==="object")Z="application/json; charset=utf-8",X=JSON.stringify($);else if(typeof $==="string")Z="text/plain; charset=utf-8",X=$;else Z="text/plain; charset=utf-8",X=String($);if(!this.headers){if(!z)return new Response(X,{status:L,headers:{"Content-Type":Z}});let G={"Content-Type":Z};return I(z,G),new Response(X,{status:L,headers:G})}if(z)_(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Z);return new Response(X,{status:L,headers:this.headers})}json($,L=200,z){if(!this.headers){if(!z)return Response.json($,{status:L,headers:{"Content-Type":"application/json; charset=utf-8"}});let Z={"Content-Type":"application/json; charset=utf-8"};return I(z,Z),Response.json($,{status:L,headers:Z})}if(z)_(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify($),{status:L,headers:this.headers})}file($,L,z=200,Z){let X=Bun.file($);if(!this.headers){if(!Z)return new Response(X,{status:z,headers:{"Content-Type":L??J($)}});let G={"Content-Type":L??J($)};return I(Z,G),new Response(X,{status:z,headers:G})}if(Z)_(this.headers,Z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",L??J($));return new Response(X,{status:z,headers:this.headers})}async ejs($,L={},z=200){console.log("this method is diabled now for some time")}redirect($,L=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",$),new Response(null,{status:L,headers:this.headers})}setCookie($,L,z={}){if(!this.headers)this.headers=new Headers;let Z=`${encodeURIComponent($)}=${encodeURIComponent(L)}`;if(z.maxAge)Z+=`; Max-Age=${z.maxAge}`;if(z.expires)Z+=`; Expires=${z.expires.toUTCString()}`;if(z.path)Z+=`; Path=${z.path}`;if(z.domain)Z+=`; Domain=${z.domain}`;if(z.secure)Z+="; Secure";if(z.httpOnly)Z+="; HttpOnly";if(z.sameSite)Z+=`; SameSite=${z.sameSite}`;return this.headers.append("Set-Cookie",Z),this}get cookies(){if(!this.parsedCookies){let $=this.req.headers.get("cookie");this.parsedCookies=$?r($):S}return this.parsedCookies}stream($){let L=new Headers(this.headers??new Headers),z=new ReadableStream({async start(Z){await $(Z),Z.close()}});return new Response(z,{headers:L})}yieldStream($){return new Response}}function _($,L){for(let z in L)$.set(z,L[z])}function I($,L){for(let z in $)L[z]=$[z]}function r($){return Object.fromEntries($.split(";").map((L)=>{let[z,...Z]=L.trim().split("=");return[z,decodeURIComponent(Z.join("="))]}))}async function a($){let L=$.headers.get("Content-Type")||"";if(!L)return{};if(!$.body)return{};if(L.startsWith("application/json"))try{return await $.json()}catch(z){throw Error("Invalid request body format")}if(L.startsWith("application/x-www-form-urlencoded")){let z=await $.text();return Object.fromEntries(new URLSearchParams(z))}if(L.startsWith("multipart/form-data")){let z=await $.formData(),Z={};for(let[X,G]of z.entries())Z[X]=G;return Z}return{error:"Unknown request body type"}}var E={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"}},f=($,L,z)=>{let Z=E[$]||E.reset,X=z?.method?E.method[z.method]||E.reset:E.reset,G=z?.status?z.status>=500?E.error:z.status>=400?E.warn:E.info:E.reset;console.log(`
1
+ function J($){switch($.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"}}var m=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],S=Object.freeze({}),B="ALL";class K{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=S;urlObject=null;constructor($,L,z,Z,X,G){this.req=$,this.server=L,this.path=z,this.param=Z,this.env=X,this.executionContext=G,this.headers=null}setHeader($,L){if(!this.headers)this.headers=new Headers;return this.headers.set($,L),this}removeHeader($){if(this.headers)this.headers.delete($);return this}set($,L){if(this.contextData===S)this.contextData={};return this.contextData[$]=L,this}get($){if(this.contextData===S)return;return this.contextData[$]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):S;return this.parsedQuery}get params(){return this.param?this.param:S}get body(){if(this.req.method==="GET")return Promise.resolve(S);if(!this.parsedBody)this.parsedBody=(async()=>{try{let $=await a(this.req);if($.error)throw Error($.error);return Object.keys($).length===0?null:$}catch($){throw Error("Invalid request body format")}})();return this.parsedBody}text($,L=200,z){if(!this.headers){if(!z)return new Response($,{status:L,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Z={"Content-Type":"text/plain; charset=utf-8"};return _(z,Z),new Response($,{status:L,headers:Z})}if(z)I(this.headers,z);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response($,{status:L,headers:this.headers})}send($,L=200,z){let Z,X;if($ instanceof Uint8Array||$ instanceof ArrayBuffer)Z="application/octet-stream",X=$;else if($!==null&&typeof $==="object")Z="application/json; charset=utf-8",X=JSON.stringify($);else if(typeof $==="string")Z="text/plain; charset=utf-8",X=$;else Z="text/plain; charset=utf-8",X=String($);if(!this.headers){if(!z)return new Response(X,{status:L,headers:{"Content-Type":Z}});let G={"Content-Type":Z};return _(z,G),new Response(X,{status:L,headers:G})}if(z)I(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Z);return new Response(X,{status:L,headers:this.headers})}json($,L=200,z){if(!this.headers){if(!z)return Response.json($,{status:L,headers:{"Content-Type":"application/json; charset=utf-8"}});let Z={"Content-Type":"application/json; charset=utf-8"};return _(z,Z),Response.json($,{status:L,headers:Z})}if(z)I(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify($),{status:L,headers:this.headers})}file($,L,z=200,Z){let X=Bun.file($);if(!this.headers){if(!Z)return new Response(X,{status:z,headers:{"Content-Type":L??J($)}});let G={"Content-Type":L??J($)};return _(Z,G),new Response(X,{status:z,headers:G})}if(Z)I(this.headers,Z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",L??J($));return new Response(X,{status:z,headers:this.headers})}async ejs($,L={},z=200){console.log("this method is diabled now for some time")}redirect($,L=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",$),new Response(null,{status:L,headers:this.headers})}setCookie($,L,z={}){if(!this.headers)this.headers=new Headers;let Z=`${encodeURIComponent($)}=${encodeURIComponent(L)}`;if(z.maxAge)Z+=`; Max-Age=${z.maxAge}`;if(z.expires)Z+=`; Expires=${z.expires.toUTCString()}`;if(z.path)Z+=`; Path=${z.path}`;if(z.domain)Z+=`; Domain=${z.domain}`;if(z.secure)Z+="; Secure";if(z.httpOnly)Z+="; HttpOnly";if(z.sameSite)Z+=`; SameSite=${z.sameSite}`;return this.headers.append("Set-Cookie",Z),this}get cookies(){if(!this.parsedCookies){let $=this.req.headers.get("cookie");this.parsedCookies=$?r($):S}return this.parsedCookies}stream($){let L=new Headers(this.headers??new Headers),z=new ReadableStream({async start(Z){await $(Z),Z.close()}});return new Response(z,{headers:L})}yieldStream($){return new Response}}function I($,L){for(let z in L)$.set(z,L[z])}function _($,L){for(let z in $)L[z]=$[z]}function r($){return Object.fromEntries($.split(";").map((L)=>{let[z,...Z]=L.trim().split("=");return[z,decodeURIComponent(Z.join("="))]}))}async function a($){let L=$.headers.get("Content-Type")||"";if(!L)return{};if(!$.body)return{};if(L.startsWith("application/json"))try{return await $.json()}catch(z){throw Error("Invalid request body format")}if(L.startsWith("application/x-www-form-urlencoded")){let z=await $.text();return Object.fromEntries(new URLSearchParams(z))}if(L.startsWith("multipart/form-data")){let z=await $.formData(),Z={};for(let[X,G]of z.entries())Z[X]=G;return Z}return{error:"Unknown request body type"}}var E={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=($,L,z)=>{let Z=E[$]||E.reset,X=z?.method?E.method[z.method]||E.reset:E.reset,G=z?.status?z.status>=500?E.error:z.status>=400?E.warn:E.info:E.reset;console.log(`
2
2
  ${Z}[${$.toUpperCase()}]${E.reset} ${L} - ${X}${z?.method||""}${E.reset}`);let V={timestamp:new Date().toISOString(),...z,status:z?.status?`${G}${z.status}${E.reset}`:void 0,method:z?.method?`${X>Z}${z.method}${E.reset}`:void 0};console.log(JSON.stringify(V,null,2)+`
3
- `)},m=($)=>{let{app:L,logger:z,logLevel:Z="info",onRequest:X,onSend:G,onError:V}=$||{};L?.addHooks("onRequest",(W)=>{W.req.startTime=Date.now(),z?.()??f(Z,"Incoming Request",{method:W.req.method,url:W.path,headers:{"user-agent":W.req.headers.get("user-agent"),"content-type":W.req.headers.get("content-type")}}),X?.(W)}),L?.addHooks("onSend",async(W,Q)=>{let N=`${Date.now()-W.req.startTime}ms`;z?.()??f(Z,"Response Sent",{method:W.req.method,url:W.url.toString(),status:Q.status,duration:N,reqId:W.get?.("requestId"),headers:{"content-type":Q.headers.get("content-type")}});let F=await G?.(W);if(F instanceof Response)return F}),L?.addHooks("onError",async(W,Q,N)=>{z?.()??f("error","Unhandled Error",{method:N.method,url:Q,status:500,error:W.message});let F=await V?.(W,Q,N);if(F instanceof Response)return F})},T=($,L,z,Z=0,X,G)=>{let V=E.method[L]||E.reset,W=Z>=500?E.error:Z>=400?E.warn:E.info,Q=G?`[${G}] `:"",N=$==="<--"?`${$} ${V}${L}${E.reset} ${z} ${Q}`:`${$} ${V}${L}${E.reset} ${z} ${W}${Z}${E.reset} ${X??""} ${Q}`;console.log(N)},t=($)=>{let L=Date.now()-$;return L<1000?`${L}ms`:`${Math.round(L/1000)}s`},c=($)=>{let{app:L,log:z,onRequest:Z,onSend:X,onError:G}=$;L.addHooks("onRequest",(V)=>{let{req:W,path:Q}=V;W.startTime=Date.now(),z?.()??T("<--",W.method,Q),Z?.(W,Q)}),L.addHooks("onSend",async(V,W)=>{let{method:Q,url:N}=V.req,F=new URL(N).pathname,M=V.get?.("requestId");z?.()??T("-->",Q,F,W?.status,t(V.req.startTime),M);let U=await X?.(V);return U instanceof Response?U:W}),L.addHooks("onError",async(V,W,Q)=>{let N=Q.path;z?.()??T(V.message,Q.method,N,500);let F=await G?.(V,N,Q);if(F instanceof Response)return F})};function u($,L){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let Z=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!Z)return z.json({message:"Unauthorized",error:"No token provided"},401);if(Z.startsWith("Bearer "))Z=Z.slice(7);let X=$?.verify(Z,L);if(!X)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);z.set("user",X)}catch(Z){let X="Invalid token";if(Z.name==="TokenExpiredError")X="Token expired";else if(Z.name==="JsonWebTokenError")X="Malformed or tampered token";return z.json({message:"Unauthorized",error:X},401)}}}function o($,L,z){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!L)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(Z)=>{try{let X=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!X)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(X.startsWith("Bearer "))X=X.slice(7);let G=$?.verify(X,z);if(!G)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let V=await L.findById(G._id).select("-password -refreshToken");if(!V)return Z.json({message:"Unauthorized: User not found"},404);Z.set("user",V);return}catch(X){let G="Invalid token";if(X.name==="TokenExpiredError")G="Token expired";else if(X.name==="JsonWebTokenError")G="Malformed or tampered token";return Z.json({message:"Unauthorized",error:G},401)}}}var D=($)=>$!==null&&typeof $==="object"&&typeof $.then==="function",v=($)=>$!==null&&typeof $==="object"&&typeof $.status==="number"&&typeof $.headers==="object";async function C($,L,z){if(!L?.length)return;for(let Z=0;Z<L.length;Z++){let X=L[Z](...z),G=X instanceof Promise?await X:X;if(G&&$!=="onRequest")return G}}async function B$($,L,z){return null}async function i($,L,z){for(let Z of $){let X=await Z(L,z);if(X)return X}}async function n($,L,z){let Z=await e($,L,z),X=D(Z)?await Z:Z;if(X)return X}async function e($,L,z){if(L.endsWith("/"))L=L.slice(0,-1);if(!$.filters.has(L))if($.filterFunction.length)for(let Z of $.filterFunction){let X=await Z(z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function K$($,L,z,Z){if(!$.filters.has(L))if($.filterFunction.length)for(let X of $.filterFunction){let G=await X(z,Z);if(G)return G}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function R($,L,z){if($.staticPath){let V=!0;if($.staticRequestPath)V=z.startsWith($.staticRequestPath);if(V){let W=await $$($,z,L);if(W)return W}}let X=$.router.find(L.req.method,"*")?.handler;if(X?.length>0){let V=await X[X.length-1](L);if(v(V))return V}let G=await Promise.resolve($.routeNotFoundFunc(L));return v(G)?G:P(404,`404 Route not found for ${z}`)}function P($,L){return new Response(JSON.stringify({error:L}),{status:$,headers:{"Content-Type":"application/json"}})}async function $$($,L,z){if(!$.staticPath)return null;let Z=`${$.staticPath}${L}`;if(await Bun.file(Z).exists()){let G=J(Z);return z.file(Z,G,200)}return null}var H=($)=>$.constructor.name==="AsyncFunction",p=($,L,z,...Z)=>{if(L.length>5)$.push(`
3
+ `)},x=($)=>{let{app:L,logger:z,logLevel:Z="info",onRequest:X,onSend:G,onError:V}=$||{};L?.addHooks("onRequest",(W)=>{W.req.startTime=Date.now(),z?.()??T(Z,"Incoming Request",{method:W.req.method,url:W.path,headers:{"user-agent":W.req.headers.get("user-agent"),"content-type":W.req.headers.get("content-type")}}),X?.(W)}),L?.addHooks("onSend",async(W,Q)=>{let N=`${Date.now()-W.req.startTime}ms`;z?.()??T(Z,"Response Sent",{method:W.req.method,url:W.url.toString(),status:Q.status,duration:N,reqId:W.get?.("requestId"),headers:{"content-type":Q.headers.get("content-type")}});let F=await G?.(W);if(F instanceof Response)return F}),L?.addHooks("onError",async(W,Q,N)=>{z?.()??T("error","Unhandled Error",{method:N.method,url:Q,status:500,error:W.message});let F=await V?.(W,Q,N);if(F instanceof Response)return F})},f=($,L,z,Z=0,X,G)=>{let V=E.method[L]||E.reset,W=Z>=500?E.error:Z>=400?E.warn:E.info,Q=G?`[${G}] `:"",N=$==="<--"?`${$} ${V}${L}${E.reset} ${z} ${Q}`:`${$} ${V}${L}${E.reset} ${z} ${W}${Z}${E.reset} ${X??""} ${Q}`;console.log(N)},t=($)=>{let L=Date.now()-$;return L<1000?`${L}ms`:`${Math.round(L/1000)}s`},u=($)=>{let{app:L,log:z,onRequest:Z,onSend:X,onError:G}=$;L.addHooks("onRequest",(V)=>{let{req:W,path:Q}=V;W.startTime=Date.now(),z?.()??f("<--",W.method,Q),Z?.(W,Q)}),L.addHooks("onSend",async(V,W)=>{let{method:Q,url:N}=V.req,F=new URL(N).pathname,D=V.get?.("requestId");z?.()??f("-->",Q,F,W?.status,t(V.req.startTime),D);let U=await X?.(V);return U instanceof Response?U:W}),L.addHooks("onError",async(V,W,Q)=>{let N=Q.path;z?.()??f(V.message,Q.method,N,500);let F=await G?.(V,N,Q);if(F instanceof Response)return F})};function c($,L){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let Z=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!Z)return z.json({message:"Unauthorized",error:"No token provided"},401);if(Z.startsWith("Bearer "))Z=Z.slice(7);let X=$?.verify(Z,L);if(!X)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);z.set("user",X)}catch(Z){let X="Invalid token";if(Z.name==="TokenExpiredError")X="Token expired";else if(Z.name==="JsonWebTokenError")X="Malformed or tampered token";return z.json({message:"Unauthorized",error:X},401)}}}function o($,L,z){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!L)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(Z)=>{try{let X=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!X)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(X.startsWith("Bearer "))X=X.slice(7);let G=$?.verify(X,z);if(!G)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let V=await L.findById(G._id).select("-password -refreshToken");if(!V)return Z.json({message:"Unauthorized: User not found"},404);Z.set("user",V);return}catch(X){let G="Invalid token";if(X.name==="TokenExpiredError")G="Token expired";else if(X.name==="JsonWebTokenError")G="Malformed or tampered token";return Z.json({message:"Unauthorized",error:G},401)}}}var C=($)=>$!==null&&typeof $==="object"&&typeof $.then==="function",v=($)=>$!==null&&typeof $==="object"&&typeof $.status==="number"&&typeof $.headers==="object";async function A($,L,z){if(!L?.length)return;for(let Z=0;Z<L.length;Z++){let X=L[Z](...z),G=X instanceof Promise?await X:X;if(G&&$!=="onRequest")return G}}async function B$($,L,z){return null}async function i($,L,z){for(let Z of $){let X=await Z(L,z);if(X)return X}}async function n($,L,z){let Z=await e($,L,z),X=C(Z)?await Z:Z;if(X)return X}async function e($,L,z){if(L.endsWith("/"))L=L.slice(0,-1);if(!$.filters.has(L))if($.filterFunction.length)for(let Z of $.filterFunction){let X=await Z(z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function K$($,L,z,Z){if(!$.filters.has(L))if($.filterFunction.length)for(let X of $.filterFunction){let G=await X(z,Z);if(G)return G}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function q($,L,z){if($.staticPath){let V=!0;if($.staticRequestPath)V=z.startsWith($.staticRequestPath);if(V){let W=await $$($,z,L);if(W)return W}}let X=$.router.find(L.req.method,"*")?.handler;if(X?.length>0){let V=await X[X.length-1](L);if(v(V))return V}let G=await Promise.resolve($.routeNotFoundFunc(L));return v(G)?G:P(404,`404 Route not found for ${z}`)}function P($,L){return new Response(JSON.stringify({error:L}),{status:$,headers:{"Content-Type":"application/json"}})}async function $$($,L,z){if(!$.staticPath)return null;let Z=`${$.staticPath}${L}`;if(await Bun.file(Z).exists()){let G=J(Z);return z.file(Z,G,200)}return null}var b=($)=>$.constructor.name==="AsyncFunction",p=($,L,z,...Z)=>{if(L.length>5)$.push(`
4
4
  for (let i = 0; i < diesel.hooks.${z}.length; i++) {
5
5
  const result = diesel.hooks.${z}[i](${Z});
6
6
  const finalResult = result instanceof Promise ? await result : result;
7
7
  if (finalResult && '${z}' !== 'onRequest') return finalResult
8
8
  }
9
- `);else L?.forEach((X,G)=>{if(H(X))$.push(`
9
+ `);else L?.forEach((X,G)=>{if(b(X))$.push(`
10
10
  const ${z}${G}Result = await diesel.hooks.${z}[${G}](${Z})
11
11
  if (${z}${G}Result && '${z}' !== 'onRequest') return ${z}${G}Result
12
12
  `);else $.push(`
@@ -30,7 +30,7 @@ ${Z}[${$.toUpperCase()}]${E.reset} ${L} - ${X}${z?.method||""}${E.reset}`);let V
30
30
  if (!pathname) {
31
31
  pathname = req.url.slice(start, i);
32
32
  }
33
- `)};var b=($)=>{let L=[],z=$?.hasPreHandlerHook?$.hooks.preHandler:[],Z=$?.hasOnSendHook?$.hooks.onSend:[];if(L$(L),L.push(`
33
+ `)};var H=($)=>{let L=[],z=$?.hasPreHandlerHook?$.hooks.preHandler:[],Z=$?.hasOnSendHook?$.hooks.onSend:[];if(L$(L),L.push(`
34
34
  const matchedRouteHandler = diesel.router.find(req.method, pathname);
35
35
  `),L.push(`
36
36
  const ctx = new Context(
@@ -68,7 +68,7 @@ ${Z}[${$.toUpperCase()}]${E.reset} ${L} - ${X}${z?.method||""}${E.reset}`);let V
68
68
  ${L.join(`
69
69
  `)}
70
70
  }
71
- `;return Function("runFilter","handleRouteNotFound","generateErrorResponse","Context","isPromise",X)(n,R,P,B,D)},h=($,L,z,...Z)=>{let X=[],G;if(typeof Z[0]==="string"||typeof Z[0]==="object")G=Z[0];let V=Z,W=$?.hasOnReqHook?$.hooks.onRequest:[],Q=$.filters.has(z),N=$.filterFunction;if(W&&W?.length>0)X.push(`
71
+ `;return Function("runFilter","handleRouteNotFound","generateErrorResponse","Context","isPromise",X)(n,q,P,K,C)},h=($,L,z,...Z)=>{let X=[],G;if(typeof Z[0]==="string"||typeof Z[0]==="object")G=Z[0];let V=Z,W=$?.hasOnReqHook?$.hooks.onRequest:[],Q=$.filters.has(z),N=$.filterFunction;if(W&&W?.length>0)X.push(`
72
72
  const onRequestResult = await runHooks(
73
73
  "onRequest",
74
74
  onRequestHooks,
@@ -91,13 +91,13 @@ ${Z}[${$.toUpperCase()}]${E.reset} ${L} - ${X}${z?.method||""}${E.reset}`);let V
91
91
  return new Response(${JSON.stringify(U)}, {
92
92
  headers: { "content-type": "application/json; charset=utf-8" }
93
93
  });
94
- `)}else if(V.length===1){let U=V[0];if(H(U))X.push(`
94
+ `)}else if(V.length===1){let U=V[0];if(b(U))X.push(`
95
95
  const response = await handlers[0](req, server);
96
96
  if (response instanceof Response) return response;
97
97
  `);else X.push(`
98
98
  const response = handlers[0](req, server);
99
99
  if (response instanceof Response) return response;
100
- `)}else V.forEach((U,Y)=>{if(H(U))X.push(`
100
+ `)}else V.forEach((U,Y)=>{if(b(U))X.push(`
101
101
  const response${Y} = await handlers[${Y}](req, server);
102
102
  if (response${Y} instanceof Response) return response${Y};
103
103
  `);else X.push(`
@@ -108,5 +108,5 @@ ${Z}[${$.toUpperCase()}]${E.reset} ${L} - ${X}${z?.method||""}${E.reset}`);let V
108
108
  ${X.join(`
109
109
  `)}
110
110
  }
111
- `;return Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",F)(i,V,C,N,W)};var z$=($)=>{let L=$.split("/");if(L[0]==="")L.shift();return L},I$=($)=>{let{groups:L,path:z}=X$($),Z=z$(z);return Z$(Z,L)},X$=($)=>{let L=[];return $=$.replace(/\{[^}]+\}/g,(z,Z)=>{let X=`@${Z}`;return L.push([X,z]),X}),{groups:L,path:$}},Z$=($,L)=>{for(let z=L.length-1;z>=0;z--){let[Z]=L[z];for(let X=$.length-1;X>=0;X--)if($[X].includes(Z)){$[X]=$[X].replace(Z,L[z][1]);break}}return $},q={},R$=($,L)=>{if($==="*")return"*";let z=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(z){let Z=`${$}#${L}`;if(!q[Z])if(z[2])q[Z]=L&&L[0]!==":"&&L[0]!=="*"?[Z,z[1],new RegExp(`^${z[2]}(?=/${L})`)]:[$,z[1],new RegExp(`^${z[2]}$`)];else q[Z]=[$,z[1],!0];return q[Z]}return null},d=($,L)=>{try{return L($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(z)=>{try{return L(z)}catch{return z}})}},G$=($)=>d($,decodeURI),K=($)=>{let L=$.indexOf("/",$.indexOf(":")+4),z=L;for(;z<$.length;z++){let Z=$.charCodeAt(z);if(Z===37){let X=$.indexOf("?",z),G=$.slice(L,X===-1?void 0:X);return G$(G.includes("%25")?G.replace(/%25/g,"%2525"):G)}else if(Z===63)break}return $.slice(L,z)},q$=($)=>{let L=$.indexOf("?",8);return L===-1?"":"?"+$.slice(L+1)},j$=($)=>{let L=K($.url);return L.length>1&&L.at(-1)==="/"?L.slice(0,-1):L},V$=($,L,...z)=>{if(z.length)L=V$(L,...z);return`${$?.[0]==="/"?"":"/"}${$}${L==="/"?"":`${$?.at(-1)==="/"?"":"/"}${L?.[0]==="/"?L.slice(1):L}`}`},f$=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let L=$.split("/"),z=[],Z="";return L.forEach((X)=>{if(X!==""&&!/\:/.test(X))Z+="/"+X;else if(/\:/.test(X))if(/\?/.test(X)){if(z.length===0&&Z==="")z.push("/");else z.push(Z);let G=X.replace("?","");Z+="/"+G,z.push(Z)}else Z+="/"+X}),z.filter((X,G,V)=>V.indexOf(X)===G)},y=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?d($,W$):$},l=($,L,z)=>{let Z;if(!z&&L&&!/[%+]/.test(L)){let V=$.indexOf(`?${L}`,8);if(V===-1)V=$.indexOf(`&${L}`,8);while(V!==-1){let W=$.charCodeAt(V+L.length+1);if(W===61){let Q=V+L.length+2,N=$.indexOf("&",Q);return y($.slice(Q,N===-1?void 0:N))}else if(W==38||isNaN(W))return"";V=$.indexOf(`&${L}`,V+1)}if(Z=/[%+]/.test($),!Z)return}let X={};Z??=/[%+]/.test($);let G=$.indexOf("?",8);while(G!==-1){let V=$.indexOf("&",G+1),W=$.indexOf("=",G);if(W>V&&V!==-1)W=-1;let Q=$.slice(G+1,W===-1?V===-1?void 0:V:W);if(Z)Q=y(Q);if(G=V,Q==="")continue;let N;if(W===-1)N="";else if(N=$.slice(W+1,V===-1?void 0:V),Z)N=y(N);if(z){if(!(X[Q]&&Array.isArray(X[Q])))X[Q]=[];X[Q].push(N)}else X[Q]??=N}return L?X[L]:X},T$=l,v$=($,L)=>{return l($,L,!0)},W$=decodeURIComponent;class j{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class g{root;globalMiddlewares;constructor(){this.root=new j,this.globalMiddlewares=[]}pushMiddleware($,L){if(!Array.isArray(L))L=[L];if($==="/"){this.globalMiddlewares.push(...L);return}let z=this.root,Z=$.split("/").filter(Boolean);for(let X of Z){let G=X;if(X.startsWith(":"))G=":";else if(X.startsWith("*"))z.middlewares.push(...L);if(!z.children[G])z.children[G]=new j;z=z.children[G]}z.middlewares.push(...L)}addMiddleware($,L){return this.pushMiddleware($,L)}insert($,L,z){let Z=Array.isArray(z)?z:[z],X=this.root;if(L==="/"){if(X.handlers[$])return;X.handlers[$]=Z,X.params=S;return}let G=L.split("/").filter(Boolean),V={};for(let W=0;W<G.length;W++){let Q=G[W],N=Q,F="";if(Q.startsWith(":"))N=":",F=Q.slice(1);if(!X.children[N])X.children[N]=new j;if(X=X.children[N],F)V[F]=W,X.paramName=F}if(X.params=V,X.handlers[$])return;X.handlers[$]=Z}add($,L,z){return this.insert($,L,z)}search($,L){let z=this.root,Z=L.split("/"),X=this.globalMiddlewares.slice(),G;for(let V=0;V<Z.length;V++){let W=Z[V];if(W.length===0)continue;if(z.children[W])z=z.children[W];else if(z.children[":"]){if(z=z.children[":"],!G)G={};G[z.paramName]=W}else if(z.children["*"]){z=z.children["*"];break}else return{params:G,middlewares:X,handler:void 0};if(z.middlewares.length>0){let Q=z.middlewares;for(let N=0;N<Q.length;N++)X.push(Q[N])}}if(z.handlers[$])return{params:G,middlewares:X,handler:z.handlers[$]};if(z.handlers[A])return{params:G,middlewares:X,handler:z.handlers[A]};return{params:G,middlewares:X,handler:void 0}}find($,L){return this.search($,L)}}class k{static create($){switch($){case"t2":return new g;case"trie":return new g;default:return new g}}}import{EventEmitter as Q$}from"events";class w{static instance;routes;tempRoutes;tempMiddlewares=new Map;router;hasOnReqHook;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#$=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;get;post;put;patch;delete;any;head;options;propfind;all;constructor($={}){x.forEach((Y)=>{this[Y.toLocaleLowerCase()]=(O,...s)=>{return this.addRoute(Y,O,s),this}});let{router:L="t2",routerInstance:z,errorFormat:Z="json",platform:X="bun",enableFileRouting:G=!1,prefixApiUrl:V="",baseApiUrl:W="",jwtSecret:Q,idleTimeOut:N=10,pipelineArchitecture:F=!1,logger:M,onError:U}=$;if(z)this.router=z;else this.router=k.create(L);if(this.errorFormat=Z,this.platform=X,!w.instance)w.instance=this;if(F)this.#$=!0;if(this.errorFormat=Z,this.emitter=new Q$,this.prefixApiUrl=V??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=N??10,this.enableFileRouter=G??!1,this.baseApiUrl=W||"",this.user_jwt_secret=Q||process.env.DIESEL_JWT_SECRET,this.tempRoutes=new Map,this.corsConfig=null,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},U)this.addHooks("onError",(Y,O)=>{console.log("Got an exception:",Y),console.log("Request Path:",O)});if(M)this.useLogger({app:this});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router($){if(!this.instance)this.instance=new w;return new Proxy(this.instance,{get(L,z,Z){return(X,G)=>{let V=G,W="";if(typeof X==="string")W=X;else if(typeof X==="function")V=X;else if(typeof X!=="string")W="";let Q=$+W;return L[z](Q,V)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.setupFilter()},authenticate:($)=>{if($?.length){let L=async(z,Z)=>{let X=z.path;for(let G of this.filters)if(X.startsWith(G))return;for(let G of $){let V=await G(z,Z);if(V)return V}};this.router.addMiddleware("/",[L])}},authenticateJwt:($)=>{if(!this.user_jwt_secret)throw Error("You must provide jwtSecret in Diesel Options to use authenticateJwt");let L=async(z)=>{let Z=z.path;for(let G of this.filters)if(Z.startsWith(G))return;let X=u($,this.user_jwt_secret)(z);if(X)return X};this.router.addMiddleware("/",L)},authenticateJwtDB:($,L)=>{if(!this.user_jwt_secret)throw Error("You must provide jwtSecret in Diesel Options to use authenticateJwt");let z=async(Z)=>{let X=Z.path;for(let V of this.filters)if(X.startsWith(V))return;let G=o($,L,this.user_jwt_secret)(Z);if(G)return G};this.router.addMiddleware("/",z)}}}redirect($,L,z){return this.any($,(Z)=>{let X=Z.params,G=L;if(X)for(let W in X)G=G.replace(`:${W}`,X[W]);let V=Z.url.search;if(V)G+=V;return Z.redirect(G,z)}),this}static($,L){return this.staticPath=$,this.staticRequestPath=L,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,L){if(typeof $!=="string")throw Error("hookName must be a string");if(typeof L!=="function")throw Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(L),this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler?.push(L),this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler?.push(L),this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend?.push(L),this.hasOnSendHook=!0;break;case"onError":this.hooks.onError?.push(L),this.hasOnError=!0;break;case"onClose":this.hooks.onClose?.push(L);break;default:throw Error(`Unknown hook type: ${$}`)}return this}useLogger($){return c($),this}useAdvancedLogger($){return m($),this}BunRoute($,L,...z){if(!L||typeof L!=="string")throw Error("give a path in string format");let Z=h(this,$.toUpperCase(),L,...z);return this.routes[L]=Z,this}listen($,...L){let z="0.0.0.0",Z=void 0,X={};for(let V of L)if(typeof V==="string")z=V;else if(typeof V==="function")Z=V;else if(typeof V==="object"&&V!==null)X=V;let G={port:$,hostname:z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)G.routes=this.routes;if(X.cert&&X.key)G.certFile=X.cert,G.keyFile=X.key;return this.serverInstance=Bun?.serve(G),Z&&Z(),this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch(){return this.tempRoutes=null,this.tempMiddlewares=null,($,L,z)=>{return this.#L($,void 0,L,z)}}fetch(){if(this.tempRoutes=null,this.tempMiddlewares=null,this.platform==="cf"||this.platform==="cloudflare"){if(this.#$){let $=b(this);return(L,z,Z)=>{return $(L,this,void 0,z,Z).catch(async(X)=>{return this.handleError(X,K(L.url),L)})}}return($,L,z)=>{return this.#L($,void 0,L,z)}}if(this.#$){let $=b(this);return(L,z)=>{return $(L,this,z,void 0,void 0).catch(async(Z)=>{return this.handleError(Z,K(L.url),L)})}}return this.#L.bind(this)}async#L($,L,z,Z){let X=K($.url),G=this.router.find($.method,X),V=new B($,L,X,G?.params||S,z,Z);try{if(this.hasOnReqHook)await C("onRequest",this.hooks.onRequest,[V]);if(G.middlewares?.length)for(let Q of G.middlewares){let N=Q(V);if(N=D(N)?await N:N,N)return N}if(this.hasPreHandlerHook){let Q=await C("preHandler",this.hooks.preHandler,[V]);if(Q)return Q}let W;if(G.handler)for(let Q of G.handler){let N=Q(V);if(W=D(N)?await N:N,W)break}if(this.hasOnSendHook){let Q=await C("onSend",this.hooks.onSend,[V,W]);if(Q)return Q}if(W)return W;return await R(this,V,X)}catch(W){return this.handleError(W,X,$)}}async handleError($,L,z){let X=this.errorFormat,G=await C("onError",this.hooks.onError,[$,L,z]);if(G)return G;if($&&typeof $==="object"&&$.name==="HTTPException"){let Q=$;if(console.error(`HTTPException on path: ${L}`,{status:Q.status,message:Q.message,cause:Q.cause,res:Q.res,stack:Q.stack}),Q.res)return Q.res;return X==="json"?Response.json({error:Q.message},{status:Q.status}):new Response(Q.message,{status:Q.status})}let V=$ instanceof Error?$.message:"Internal Server Error",W=$ instanceof Error?$.stack:void 0;if(console.error(`Error on path: ${L}`,{message:V,stack:W}),X==="json"){let Q={error:V,...{stack:W},path:L};return Response.json(Q,{status:500,headers:{"Content-Type":"application/json"}})}else{let Q=`Error: ${V}
112
- Stack: ${W}`;return new Response(Q,{headers:{"Content-Type":"text/plain"},status:500})}}mount($,L){let z=typeof L==="function"?L:L.fetch(),Z=$.endsWith("/*")?$.slice(0,-1):$,X=Z==="/"?0:Z.length;this.all($,(G)=>{let V=new URL(G.req.url);V.pathname=V.pathname.slice(X)||"/";let W=new Request(V,G.req);return z(W,G.server,G.env,G.executionContext)})}route($,L){$=$&&$.length>0?$:L?.prefixApiUrl;let z=L?.tempRoutes??new Map;for(let[Z,X]of z.entries()){let G=Z.replace(/::\w+$/,""),V=`${$}${G}`,W=X.method;this.router.add(W,V,X.handlers)}for(let[Z,X]of L?.tempMiddlewares?.entries()){let G=Z==="/"?$||"/":`${$}${Z}`;this.router.addMiddleware(G,X)}return L=null,this}sub($,L){return this.mount($,L)}addMiddlewareInRouter($,L){this.router.addMiddleware($,L)}addRoute($,L,z){if(typeof L!=="string")throw Error(`Error in ${z[z.length-1]}: Path must be a string. Received: ${typeof L}`);if(typeof $!=="string")throw Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(L+"::"+$,{method:$,handlers:z}),$=$==="ANY"?A:$,this.router.add($,L,z)}use($,...L){if(typeof $==="string"){let z=$==="/"?"/":$;if(!this.tempMiddlewares?.has(z))this.tempMiddlewares?.set(z,[]);this.tempMiddlewares?.get(z).push(...L),this.router.addMiddleware(z,L)}else if(typeof $==="function"){let z=[$,...L];if(!this.tempMiddlewares?.has("/"))this.tempMiddlewares?.set("/",[]);this.tempMiddlewares?.get("/").push(...L),this.router.addMiddleware("/",z)}return this}routeNotFound($){return this.routeNotFoundFunc=$,this}onMethod($,L,...z){let Z=Array.isArray($)?$:[$];for(let X of Z){let G=X.toLowerCase();if(G in this)this[G](L,...z);else this.addRoute(X.toUpperCase(),L,z)}return this}on($,L){return this.emitter.on($,L),this}emit($,...L){return this.emitter.emit($,...L),this}}export{w as default};
111
+ `;return Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",F)(i,V,A,N,W)};var z$=($)=>{let L=$.split("/");if(L[0]==="")L.shift();return L},_$=($)=>{let{groups:L,path:z}=X$($),Z=z$(z);return Z$(Z,L)},X$=($)=>{let L=[];return $=$.replace(/\{[^}]+\}/g,(z,Z)=>{let X=`@${Z}`;return L.push([X,z]),X}),{groups:L,path:$}},Z$=($,L)=>{for(let z=L.length-1;z>=0;z--){let[Z]=L[z];for(let X=$.length-1;X>=0;X--)if($[X].includes(Z)){$[X]=$[X].replace(Z,L[z][1]);break}}return $},R={},q$=($,L)=>{if($==="*")return"*";let z=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(z){let Z=`${$}#${L}`;if(!R[Z])if(z[2])R[Z]=L&&L[0]!==":"&&L[0]!=="*"?[Z,z[1],new RegExp(`^${z[2]}(?=/${L})`)]:[$,z[1],new RegExp(`^${z[2]}$`)];else R[Z]=[$,z[1],!0];return R[Z]}return null},d=($,L)=>{try{return L($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(z)=>{try{return L(z)}catch{return z}})}},G$=($)=>d($,decodeURI),g=($)=>{let L=$.indexOf("/",$.indexOf(":")+4),z=L;for(;z<$.length;z++){let Z=$.charCodeAt(z);if(Z===37){let X=$.indexOf("?",z),G=$.slice(L,X===-1?void 0:X);return G$(G.includes("%25")?G.replace(/%25/g,"%2525"):G)}else if(Z===63)break}return $.slice(L,z)},R$=($)=>{let L=$.indexOf("?",8);return L===-1?"":"?"+$.slice(L+1)},j$=($)=>{let L=g($.url);return L.length>1&&L.at(-1)==="/"?L.slice(0,-1):L},V$=($,L,...z)=>{if(z.length)L=V$(L,...z);return`${$?.[0]==="/"?"":"/"}${$}${L==="/"?"":`${$?.at(-1)==="/"?"":"/"}${L?.[0]==="/"?L.slice(1):L}`}`},T$=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let L=$.split("/"),z=[],Z="";return L.forEach((X)=>{if(X!==""&&!/\:/.test(X))Z+="/"+X;else if(/\:/.test(X))if(/\?/.test(X)){if(z.length===0&&Z==="")z.push("/");else z.push(Z);let G=X.replace("?","");Z+="/"+G,z.push(Z)}else Z+="/"+X}),z.filter((X,G,V)=>V.indexOf(X)===G)},y=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?d($,W$):$},l=($,L,z)=>{let Z;if(!z&&L&&!/[%+]/.test(L)){let V=$.indexOf(`?${L}`,8);if(V===-1)V=$.indexOf(`&${L}`,8);while(V!==-1){let W=$.charCodeAt(V+L.length+1);if(W===61){let Q=V+L.length+2,N=$.indexOf("&",Q);return y($.slice(Q,N===-1?void 0:N))}else if(W==38||isNaN(W))return"";V=$.indexOf(`&${L}`,V+1)}if(Z=/[%+]/.test($),!Z)return}let X={};Z??=/[%+]/.test($);let G=$.indexOf("?",8);while(G!==-1){let V=$.indexOf("&",G+1),W=$.indexOf("=",G);if(W>V&&V!==-1)W=-1;let Q=$.slice(G+1,W===-1?V===-1?void 0:V:W);if(Z)Q=y(Q);if(G=V,Q==="")continue;let N;if(W===-1)N="";else if(N=$.slice(W+1,V===-1?void 0:V),Z)N=y(N);if(z){if(!(X[Q]&&Array.isArray(X[Q])))X[Q]=[];X[Q].push(N)}else X[Q]??=N}return L?X[L]:X},f$=l,v$=($,L)=>{return l($,L,!0)},W$=decodeURIComponent;class j{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class w{root;globalMiddlewares;constructor(){this.root=new j,this.globalMiddlewares=[]}pushMiddleware($,L){if(!Array.isArray(L))L=[L];if($==="/"){this.globalMiddlewares.push(...L);return}let z=this.root,Z=$.split("/").filter(Boolean);for(let X of Z){let G=X;if(X.startsWith(":"))G=":";else if(X.startsWith("*"))z.middlewares.push(...L);if(!z.children[G])z.children[G]=new j;z=z.children[G]}z.middlewares.push(...L)}addMiddleware($,L){return this.pushMiddleware($,L)}insert($,L,z){let Z=Array.isArray(z)?z:[z],X=this.root;if(L==="/"){if(X.handlers[$])return;X.handlers[$]=Z,X.params=S;return}let G=L.split("/").filter(Boolean),V={};for(let W=0;W<G.length;W++){let Q=G[W],N=Q,F="";if(Q.startsWith(":"))N=":",F=Q.slice(1);if(!X.children[N])X.children[N]=new j;if(X=X.children[N],F)V[F]=W,X.paramName=F}if(X.params=V,X.handlers[$])return;X.handlers[$]=Z}add($,L,z){return this.insert($,L,z)}search($,L){let z=this.root,Z=L.split("/"),X=this.globalMiddlewares.slice(),G;for(let V=0;V<Z.length;V++){let W=Z[V];if(W.length===0)continue;if(z.children[W])z=z.children[W];else if(z.children[":"]){if(z=z.children[":"],!G)G={};G[z.paramName]=W}else if(z.children["*"]){z=z.children["*"];break}else return{params:G,middlewares:X,handler:void 0};if(z.middlewares.length>0){let Q=z.middlewares;for(let N=0;N<Q.length;N++)X.push(Q[N])}}if(z.handlers[$])return{params:G,middlewares:X,handler:z.handlers[$]};if(z.handlers[B])return{params:G,middlewares:X,handler:z.handlers[B]};return{params:G,middlewares:X,handler:void 0}}find($,L){return this.search($,L)}}class k{static create($){switch($){case"t2":return new w;case"trie":return new w;default:return new w}}}import{EventEmitter as Q$}from"events";class M{static instance;routes;tempRoutes;tempMiddlewares=new Map;router;hasOnReqHook;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#$=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;get;post;put;patch;delete;any;head;options;propfind;all;constructor($={}){m.forEach((Y)=>{this[Y.toLocaleLowerCase()]=(O,...s)=>{return this.addRoute(Y,O,s),this}});let{router:L="t2",routerInstance:z,errorFormat:Z="json",platform:X="bun",enableFileRouting:G=!1,prefixApiUrl:V="",baseApiUrl:W="",jwtSecret:Q,idleTimeOut:N=10,pipelineArchitecture:F=!1,logger:D,onError:U}=$;if(z)this.router=z;else this.router=k.create(L);if(this.errorFormat=Z,this.platform=X,!M.instance)M.instance=this;if(F)this.#$=!0;if(this.errorFormat=Z,this.emitter=new Q$,this.prefixApiUrl=V??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=N??10,this.enableFileRouter=G??!1,this.baseApiUrl=W||"",this.user_jwt_secret=Q||process.env.DIESEL_JWT_SECRET,this.tempRoutes=new Map,this.corsConfig=null,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},U)this.addHooks("onError",(Y,O)=>{console.log("Got an exception:",Y),console.log("Request Path:",O)});if(D)this.useLogger({app:this});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router($){if(!this.instance)this.instance=new M;return new Proxy(this.instance,{get(L,z,Z){return(X,G)=>{let V=G,W="";if(typeof X==="string")W=X;else if(typeof X==="function")V=X;else if(typeof X!=="string")W="";let Q=$+W;return L[z](Q,V)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.setupFilter()},authenticate:($)=>{if($?.length){let L=async(z,Z)=>{let X=z.path;for(let G of this.filters)if(X.startsWith(G))return;for(let G of $){let V=await G(z,Z);if(V)return V}};this.router.addMiddleware("/",[L])}},authenticateJwt:($)=>{if(!this.user_jwt_secret)throw Error("You must provide jwtSecret in Diesel Options to use authenticateJwt");let L=async(z)=>{let Z=z.path;for(let G of this.filters)if(Z.startsWith(G))return;let X=c($,this.user_jwt_secret)(z);if(X)return X};this.router.addMiddleware("/",L)},authenticateJwtDB:($,L)=>{if(!this.user_jwt_secret)throw Error("You must provide jwtSecret in Diesel Options to use authenticateJwt");let z=async(Z)=>{let X=Z.path;for(let V of this.filters)if(X.startsWith(V))return;let G=o($,L,this.user_jwt_secret)(Z);if(G)return G};this.router.addMiddleware("/",z)}}}redirect($,L,z){return this.any($,(Z)=>{let X=Z.params,G=L;if(X)for(let W in X)G=G.replace(`:${W}`,X[W]);let V=Z.url.search;if(V)G+=V;return Z.redirect(G,z)}),this}static($,L){return this.staticPath=$,this.staticRequestPath=L,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,L){if(typeof $!=="string")throw Error("hookName must be a string");if(typeof L!=="function")throw Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(L),this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler?.push(L),this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler?.push(L),this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend?.push(L),this.hasOnSendHook=!0;break;case"onError":this.hooks.onError?.push(L),this.hasOnError=!0;break;case"onClose":this.hooks.onClose?.push(L);break;default:throw Error(`Unknown hook type: ${$}`)}return this}useLogger($){return u($),this}useAdvancedLogger($){return x($),this}BunRoute($,L,...z){if(!L||typeof L!=="string")throw Error("give a path in string format");let Z=h(this,$.toUpperCase(),L,...z);return this.routes[L]=Z,this}listen($,...L){let z="0.0.0.0",Z=void 0,X={};for(let V of L)if(typeof V==="string")z=V;else if(typeof V==="function")Z=V;else if(typeof V==="object"&&V!==null)X=V;let G={port:$,hostname:z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)G.routes=this.routes;if(X.cert&&X.key)G.certFile=X.cert,G.keyFile=X.key;return this.serverInstance=Bun?.serve(G),Z&&Z(),this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch(){return this.tempRoutes=null,this.tempMiddlewares=null,($,L,z)=>{return this.#L($,void 0,L,z)}}fetch(){if(this.tempRoutes=null,this.tempMiddlewares=null,this.platform==="cf"||this.platform==="cloudflare"){if(this.#$){let $=H(this);return(L,z,Z)=>{return $(L,this,void 0,z,Z).catch(async(X)=>{return this.handleError(X,g(L.url),L)})}}return($,L,z)=>{return this.#L($,void 0,L,z)}}if(this.#$){let $=H(this);return(L,z)=>{return $(L,this,z,void 0,void 0).catch(async(Z)=>{return this.handleError(Z,g(L.url),L)})}}return this.#L.bind(this)}#L($,L,z,Z){let X=g($.url),G=this.router.find($.method,X),V=new K($,L,X,G?.params||S,z,Z);return this.#z(V,G).catch((W)=>this.handleError(W,X,$))}async#z($,L){if(this.hasOnReqHook)await A("onRequest",this.hooks.onRequest,[$]);if(L.middlewares?.length)for(let Z of L.middlewares){let X=Z($);if(X=C(X)?await X:X,X)return X}if(this.hasPreHandlerHook){let Z=await A("preHandler",this.hooks.preHandler,[$]);if(Z)return Z}let z;if(L.handler)for(let Z of L.handler){let X=Z($);if(z=C(X)?await X:X,z)break}if(this.hasOnSendHook){let Z=await A("onSend",this.hooks.onSend,[$,z]);if(Z)return Z}if(z)return z;return await q(this,$,$.path)}async handleError($,L,z){let X=this.errorFormat,G=await A("onError",this.hooks.onError,[$,L,z]);if(G)return G;if($&&typeof $==="object"&&$.name==="HTTPException"){let Q=$;if(console.error(`HTTPException on path: ${L}`,{status:Q.status,message:Q.message,cause:Q.cause,res:Q.res,stack:Q.stack}),Q.res)return Q.res;return X==="json"?Response.json({error:Q.message},{status:Q.status}):new Response(Q.message,{status:Q.status})}let V=$ instanceof Error?$.message:"Internal Server Error",W=$ instanceof Error?$.stack:void 0;if(console.error(`Error on path: ${L}`,{message:V,stack:W}),X==="json"){let Q={error:V,...{stack:W},path:L};return Response.json(Q,{status:500,headers:{"Content-Type":"application/json"}})}else{let Q=`Error: ${V}
112
+ Stack: ${W}`;return new Response(Q,{headers:{"Content-Type":"text/plain"},status:500})}}mount($,L){let z=$.endsWith("/*")?$.slice(0,-2):$,Z=z==="/"?0:z.length,X=typeof L==="function"?L:L.fetch();this.all($,async(G)=>{let V=G.path?.slice(Z)||"/",W=new URL(G.req.url);W.pathname=V;let Q=new Request(W,G.req),N=await X(Q,G.server,G.env,G.executionContext);if(!G.headers||!N)return N;let F=new Headers(N.headers);for(let[D,U]of G.headers)if(!F.has(D))F.set(D,U);return new Response(N.body,{status:N.status,statusText:N.statusText,headers:F})})}sub($,L){let z=$.endsWith("/*")?$.slice(0,-2):$,Z=z==="/"?0:z.length;this.all($,(X)=>{let G=X.path?.slice(Z)||"/",V=L.router.find(X.req.method,G);return X.path=G,X.param=V?.params||S,L.#z(X,V).catch((W)=>this.handleError(W,G,X.req))})}route($,L){$=$&&$.length>0?$:L?.prefixApiUrl;let z=L?.tempRoutes??new Map;for(let[Z,X]of z.entries()){let G=Z.replace(/::\w+$/,""),V=`${$}${G}`,W=X.method;this.router.add(W,V,X.handlers)}for(let[Z,X]of L?.tempMiddlewares?.entries()){let G=Z==="/"?$||"/":`${$}${Z}`;this.router.addMiddleware(G,X)}return L=null,this}addMiddlewareInRouter($,L){this.router.addMiddleware($,L)}addRoute($,L,z){if(typeof L!=="string")throw Error(`Error in ${z[z.length-1]}: Path must be a string. Received: ${typeof L}`);if(typeof $!=="string")throw Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(L+"::"+$,{method:$,handlers:z}),$=$==="ANY"?B:$,this.router.add($,L,z)}use($,...L){if(typeof $==="string"){let z=$==="/"?"/":$;if(!this.tempMiddlewares?.has(z))this.tempMiddlewares?.set(z,[]);this.tempMiddlewares?.get(z).push(...L),this.router.addMiddleware(z,L)}else if(typeof $==="function"){let z=[$,...L];if(!this.tempMiddlewares?.has("/"))this.tempMiddlewares?.set("/",[]);this.tempMiddlewares?.get("/").push(...L),this.router.addMiddleware("/",z)}return this}routeNotFound($){return this.routeNotFoundFunc=$,this}onMethod($,L,...z){let Z=Array.isArray($)?$:[$];for(let X of Z){let G=X.toLowerCase();if(G in this)this[G](L,...z);else this.addRoute(X.toUpperCase(),L,z)}return this}on($,L){return this.emitter.on($,L),this}emit($,...L){return this.emitter.emit($,...L),this}}export{M as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "2.0.5",
3
+ "version": "2.1.0",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -70,10 +70,10 @@
70
70
  "import": "./dist/http-exception.js",
71
71
  "require": "./dist/http-exception.js"
72
72
  },
73
- "./node":{
73
+ "./node": {
74
74
  "types": "./dist/adaptor/node/main.d.ts",
75
- "import":"./dist/adaptor/node/main.js",
76
- "require":"./dist/adaptor/node/main.js"
75
+ "import": "./dist/adaptor/node/main.js",
76
+ "require": "./dist/adaptor/node/main.js"
77
77
  }
78
78
  },
79
79
  "scripts": {
@@ -1,3 +0,0 @@
1
- import { Server } from "bun";
2
- import Diesel from "./main";
3
- export default function handleRequest(req: Request, server: Server, diesel: Diesel, env?: Record<string, any>, executionContext?: any): Promise<Response | undefined>;
@@ -1 +0,0 @@
1
- function E(L){switch(L.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"}}var h=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],Q=Object.freeze({}),m="ALL";class J{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=Q;urlObject=null;constructor(L,w,z,N,A,W){this.req=L,this.server=w,this.path=z,this.param=N,this.env=A,this.executionContext=W,this.headers=null}setHeader(L,w){if(!this.headers)this.headers=new Headers;return this.headers.set(L,w),this}removeHeader(L){if(this.headers)this.headers.delete(L);return this}set(L,w){if(this.contextData===Q)this.contextData={};return this.contextData[L]=w,this}get(L){if(this.contextData===Q)return;return this.contextData[L]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):Q;return this.parsedQuery}get params(){return this.param?this.param:Q}get body(){if(this.req.method==="GET")return Promise.resolve(Q);if(!this.parsedBody)this.parsedBody=(async()=>{try{let L=await P(this.req);if(L.error)throw Error(L.error);return Object.keys(L).length===0?null:L}catch(L){throw Error("Invalid request body format")}})();return this.parsedBody}text(L,w=200,z){if(!this.headers){if(!z)return new Response(L,{status:w,headers:{"Content-Type":"text/plain; charset=utf-8"}});let N={"Content-Type":"text/plain; charset=utf-8"};return U(z,N),new Response(L,{status:w,headers:N})}if(z)O(this.headers,z);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response(L,{status:w,headers:this.headers})}send(L,w=200,z){let N,A;if(L instanceof Uint8Array||L instanceof ArrayBuffer)N="application/octet-stream",A=L;else if(L!==null&&typeof L==="object")N="application/json; charset=utf-8",A=JSON.stringify(L);else if(typeof L==="string")N="text/plain; charset=utf-8",A=L;else N="text/plain; charset=utf-8",A=String(L);if(!this.headers){if(!z)return new Response(A,{status:w,headers:{"Content-Type":N}});let W={"Content-Type":N};return U(z,W),new Response(A,{status:w,headers:W})}if(z)O(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",N);return new Response(A,{status:w,headers:this.headers})}json(L,w=200,z){if(!this.headers){if(!z)return Response.json(L,{status:w,headers:{"Content-Type":"application/json; charset=utf-8"}});let N={"Content-Type":"application/json; charset=utf-8"};return U(z,N),Response.json(L,{status:w,headers:N})}if(z)O(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(L),{status:w,headers:this.headers})}file(L,w,z=200,N){let A=Bun.file(L);if(!this.headers){if(!N)return new Response(A,{status:z,headers:{"Content-Type":w??E(L)}});let W={"Content-Type":w??E(L)};return U(N,W),new Response(A,{status:z,headers:W})}if(N)O(this.headers,N);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",w??E(L));return new Response(A,{status:z,headers:this.headers})}async ejs(L,w={},z=200){console.log("this method is diabled now for some time")}redirect(L,w=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",L),new Response(null,{status:w,headers:this.headers})}setCookie(L,w,z={}){if(!this.headers)this.headers=new Headers;let N=`${encodeURIComponent(L)}=${encodeURIComponent(w)}`;if(z.maxAge)N+=`; Max-Age=${z.maxAge}`;if(z.expires)N+=`; Expires=${z.expires.toUTCString()}`;if(z.path)N+=`; Path=${z.path}`;if(z.domain)N+=`; Domain=${z.domain}`;if(z.secure)N+="; Secure";if(z.httpOnly)N+="; HttpOnly";if(z.sameSite)N+=`; SameSite=${z.sameSite}`;return this.headers.append("Set-Cookie",N),this}get cookies(){if(!this.parsedCookies){let L=this.req.headers.get("cookie");this.parsedCookies=L?T(L):Q}return this.parsedCookies}stream(L){let w=new Headers(this.headers??new Headers),z=new ReadableStream({async start(N){await L(N),N.close()}});return new Response(z,{headers:w})}yieldStream(L){return new Response}}function O(L,w){for(let z in w)L.set(z,w[z])}function U(L,w){for(let z in L)w[z]=L[z]}function T(L){return Object.fromEntries(L.split(";").map((w)=>{let[z,...N]=w.trim().split("=");return[z,decodeURIComponent(N.join("="))]}))}async function P(L){let w=L.headers.get("Content-Type")||"";if(!w)return{};if(!L.body)return{};if(w.startsWith("application/json"))try{return await L.json()}catch(z){throw Error("Invalid request body format")}if(w.startsWith("application/x-www-form-urlencoded")){let z=await L.text();return Object.fromEntries(new URLSearchParams(z))}if(w.startsWith("multipart/form-data")){let z=await L.formData(),N={};for(let[A,W]of z.entries())N[A]=W;return N}return{error:"Unknown request body type"}}var F=(L)=>L!==null&&typeof L==="object"&&typeof L.then==="function",j=(L)=>L!==null&&typeof L==="object"&&typeof L.status==="number"&&typeof L.headers==="object";async function B(L,w,z){if(!w?.length)return;for(let N=0;N<w.length;N++){let A=w[N](...z),W=A instanceof Promise?await A:A;if(W&&L!=="onRequest")return W}}async function l(L,w,z){return null}async function r(L,w,z){for(let N of L){let A=await N(w,z);if(A)return A}}async function a(L,w,z){let N=await R(L,w,z),A=F(N)?await N:N;if(A)return A}async function R(L,w,z){if(w.endsWith("/"))w=w.slice(0,-1);if(!L.filters.has(w))if(L.filterFunction.length)for(let N of L.filterFunction){let A=await N(z);if(A)return A}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function s(L,w,z,N){if(!L.filters.has(w))if(L.filterFunction.length)for(let A of L.filterFunction){let W=await A(z,N);if(W)return W}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function K(L,w,z){if(L.staticPath){let X=!0;if(L.staticRequestPath)X=z.startsWith(L.staticRequestPath);if(X){let Z=await g(L,z,w);if(Z)return Z}}let A=L.router.find(w.req.method,"*")?.handler;if(A?.length>0){let X=await A[A.length-1](w);if(j(X))return X}let W=await Promise.resolve(L.routeNotFoundFunc(w));return j(W)?W:M(404,`404 Route not found for ${z}`)}function M(L,w){return new Response(JSON.stringify({error:w}),{status:L,headers:{"Content-Type":"application/json"}})}async function g(L,w,z){if(!L.staticPath)return null;let N=`${L.staticPath}${w}`;if(await Bun.file(N).exists()){let W=E(N);return z.file(N,W,200)}return null}var q=(L)=>{let w=L.split("/");if(w[0]==="")w.shift();return w},e=(L)=>{let{groups:w,path:z}=I(L),N=q(z);return b(N,w)},I=(L)=>{let w=[];return L=L.replace(/\{[^}]+\}/g,(z,N)=>{let A=`@${N}`;return w.push([A,z]),A}),{groups:w,path:L}},b=(L,w)=>{for(let z=w.length-1;z>=0;z--){let[N]=w[z];for(let A=L.length-1;A>=0;A--)if(L[A].includes(N)){L[A]=L[A].replace(N,w[z][1]);break}}return L},Y={},LL=(L,w)=>{if(L==="*")return"*";let z=L.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(z){let N=`${L}#${w}`;if(!Y[N])if(z[2])Y[N]=w&&w[0]!==":"&&w[0]!=="*"?[N,z[1],new RegExp(`^${z[2]}(?=/${w})`)]:[L,z[1],new RegExp(`^${z[2]}$`)];else Y[N]=[L,z[1],!0];return Y[N]}return null},f=(L,w)=>{try{return w(L)}catch{return L.replace(/(?:%[0-9A-Fa-f]{2})+/g,(z)=>{try{return w(z)}catch{return z}})}},v=(L)=>f(L,decodeURI),_=(L)=>{let w=L.indexOf("/",L.indexOf(":")+4),z=w;for(;z<L.length;z++){let N=L.charCodeAt(z);if(N===37){let A=L.indexOf("?",z),W=L.slice(w,A===-1?void 0:A);return v(W.includes("%25")?W.replace(/%25/g,"%2525"):W)}else if(N===63)break}return L.slice(w,z)},wL=(L)=>{let w=L.indexOf("?",8);return w===-1?"":"?"+L.slice(w+1)},zL=(L)=>{let w=_(L.url);return w.length>1&&w.at(-1)==="/"?w.slice(0,-1):w},H=(L,w,...z)=>{if(z.length)w=H(w,...z);return`${L?.[0]==="/"?"":"/"}${L}${w==="/"?"":`${L?.at(-1)==="/"?"":"/"}${w?.[0]==="/"?w.slice(1):w}`}`},NL=(L)=>{if(L.charCodeAt(L.length-1)!==63||!L.includes(":"))return null;let w=L.split("/"),z=[],N="";return w.forEach((A)=>{if(A!==""&&!/\:/.test(A))N+="/"+A;else if(/\:/.test(A))if(/\?/.test(A)){if(z.length===0&&N==="")z.push("/");else z.push(N);let W=A.replace("?","");N+="/"+W,z.push(N)}else N+="/"+A}),z.filter((A,W,X)=>X.indexOf(A)===W)},S=(L)=>{if(!/[%+]/.test(L))return L;if(L.indexOf("+")!==-1)L=L.replace(/\+/g," ");return L.indexOf("%")!==-1?f(L,x):L},C=(L,w,z)=>{let N;if(!z&&w&&!/[%+]/.test(w)){let X=L.indexOf(`?${w}`,8);if(X===-1)X=L.indexOf(`&${w}`,8);while(X!==-1){let Z=L.charCodeAt(X+w.length+1);if(Z===61){let $=X+w.length+2,G=L.indexOf("&",$);return S(L.slice($,G===-1?void 0:G))}else if(Z==38||isNaN(Z))return"";X=L.indexOf(`&${w}`,X+1)}if(N=/[%+]/.test(L),!N)return}let A={};N??=/[%+]/.test(L);let W=L.indexOf("?",8);while(W!==-1){let X=L.indexOf("&",W+1),Z=L.indexOf("=",W);if(Z>X&&X!==-1)Z=-1;let $=L.slice(W+1,Z===-1?X===-1?void 0:X:Z);if(N)$=S($);if(W=X,$==="")continue;let G;if(Z===-1)G="";else if(G=L.slice(Z+1,X===-1?void 0:X),N)G=S(G);if(z){if(!(A[$]&&Array.isArray(A[$])))A[$]=[];A[$].push(G)}else A[$]??=G}return w?A[w]:A},AL=C,WL=(L,w)=>{return C(L,w,!0)},x=decodeURIComponent;async function k(L,w,z,N,A){let W=_(L.url),X=z.router.find(L.method,W),Z=new J(L,w,W,X?.params||Q,N,A);if(z.hasPreHandlerHook){let V=await B("preHandler",z.hooks.preHandler,[Z]);if(V)return V}let $,G=X?.handler;if(G.length===1){let V=G[0](Z);$=F(V)?await V:V}else for(let V=0;V<G.length;V++){let D=G[V](Z);if($=F(D)?await D:D,$)break}if(z.hasOnSendHook){let V=await B("onSend",z.hooks.onSend,[Z,$]);if(V)return V}return $??await K(z,Z,W)}export{k as default};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
File without changes
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};