diesel-core 2.0.4 → 2.0.5

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.
@@ -0,0 +1 @@
1
+ function c(t){let s={};if(console.log(t.socket),"headers"in t)if("get"in t.headers)s=Object.fromEntries(t?.headers?.entries());else s=t.headers;let o=s["x-forwarded-proto"]?.split(",")[0]||("socket"in t&&t.socket?.encrypted?"https":"http"),r=s.host||"",n,e=s["x-forwarded-for"];if(e)n=e.split(",")[0].trim();else if("socket"in t&&t.socket?.remoteAddress)n=t.socket.remoteAddress;let i="url"in t?t.url:`${o}://${r}${t.url||""}`;return{protocol:o,host:r,url:i,ip:n,headers:s}}export{c as connInfo};
@@ -0,0 +1 @@
1
+ import*as A from"node:http";async function B(g){let x=`${g.headers["x-forwarded-proto"]?.split(",")[0]||"http"}://${g.headers.host}${g.url}`,m={method:g.method,headers:g.headers,body:null};if(g.method!=="GET"&&g.method!=="PUT")m.body=new ReadableStream({start(y){g.on("data",(z)=>y.enqueue(new Uint8Array(z))),g.on("end",()=>y.close()),g.on("error",(z)=>y.error(z))}});return new Request(x,m)}async function C(g,j){j.writeHead(g.status,Object.fromEntries(g.headers));let x=g.body?.getReader();if(x){let m;while(!(m=await x.read()).done)j.write(Buffer.from(m.value))}j.end()}function D(g){let j=A.createServer(async(x,m)=>{let y=await B(x),z=await g.fetch(y,j);await C(z,m)});return j.listen(g.port??3000,()=>console.log(`node server running on port ${g.port??3000}`)),j}export{D as serve};
@@ -1,2 +1,3 @@
1
1
  export declare const supportedMethods: string[];
2
2
  export declare const EMPTY_OBJ: Readonly<{}>;
3
+ export declare const ALL_METHOD = "ALL";
package/dist/constant.js CHANGED
@@ -1 +1 @@
1
- var e=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],t=Object.freeze({});export{e as supportedMethods,t as EMPTY_OBJ};
1
+ var e=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],t=Object.freeze({}),o="ALL";export{e as supportedMethods,t as EMPTY_OBJ,o as ALL_METHOD};
package/dist/ctx.d.ts CHANGED
@@ -34,6 +34,3 @@ export declare class Context {
34
34
  stream(callback: (controller: ReadableStreamDefaultController) => void): Response;
35
35
  yieldStream(callback: () => AsyncIterable<any>): Response;
36
36
  }
37
- export declare function extractParam(paramNames: string[], incomingPath: string): Record<string, string>;
38
- export declare function extractDynamicParams(originalPath: string, incomingPath: string): Record<string, string> | null;
39
- export declare function parseParams(inComingpath: string | null, param: Record<string, number> | null): Record<string, any>;
package/dist/ctx.js CHANGED
@@ -1 +1 @@
1
- function G(w){switch(w.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 F=Object.freeze({});class V{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=F;urlObject=null;constructor(w,A,x,L,f,I){this.req=w,this.server=A,this.path=x,this.param=L,this.env=f,this.executionContext=I,this.headers=null}setHeader(w,A){if(!this.headers)this.headers=new Headers;return this.headers.set(w,A),this}removeHeader(w){if(this.headers)this.headers.delete(w);return this}set(w,A){if(this.contextData===F)this.contextData={};return this.contextData[w]=A,this}get(w){if(this.contextData===F)return;return this.contextData[w]}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):F;return this.parsedQuery}get params(){return this.param?this.param:F}get body(){if(this.req.method==="GET")return Promise.resolve(F);if(!this.parsedBody)this.parsedBody=(async()=>{try{let w=await Z(this.req);if(w.error)throw Error(w.error);return Object.keys(w).length===0?null:w}catch(w){throw Error("Invalid request body format")}})();return this.parsedBody}text(w,A=200,x){if(!this.headers){if(!x)return new Response(w,{status:A,headers:{"Content-Type":"text/plain; charset=utf-8"}});let L={"Content-Type":"text/plain; charset=utf-8"};return U(x,L),new Response(w,{status:A,headers:L})}if(x)R(this.headers,x);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response(w,{status:A,headers:this.headers})}send(w,A=200,x){let L,f;if(w instanceof Uint8Array||w instanceof ArrayBuffer)L="application/octet-stream",f=w;else if(w!==null&&typeof w==="object")L="application/json; charset=utf-8",f=JSON.stringify(w);else if(typeof w==="string")L="text/plain; charset=utf-8",f=w;else L="text/plain; charset=utf-8",f=String(w);if(!this.headers){if(!x)return new Response(f,{status:A,headers:{"Content-Type":L}});let I={"Content-Type":L};return U(x,I),new Response(f,{status:A,headers:I})}if(x)R(this.headers,x);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",L);return new Response(f,{status:A,headers:this.headers})}json(w,A=200,x){if(!this.headers){if(!x)return Response.json(w,{status:A,headers:{"Content-Type":"application/json; charset=utf-8"}});let L={"Content-Type":"application/json; charset=utf-8"};return U(x,L),Response.json(w,{status:A,headers:L})}if(x)R(this.headers,x);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(w),{status:A,headers:this.headers})}file(w,A,x=200,L){let f=Bun.file(w);if(!this.headers){if(!L)return new Response(f,{status:x,headers:{"Content-Type":A??G(w)}});let I={"Content-Type":A??G(w)};return U(L,I),new Response(f,{status:x,headers:I})}if(L)R(this.headers,L);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",A??G(w));return new Response(f,{status:x,headers:this.headers})}async ejs(w,A={},x=200){console.log("this method is diabled now for some time")}redirect(w,A=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",w),new Response(null,{status:A,headers:this.headers})}setCookie(w,A,x={}){if(!this.headers)this.headers=new Headers;let L=`${encodeURIComponent(w)}=${encodeURIComponent(A)}`;if(x.maxAge)L+=`; Max-Age=${x.maxAge}`;if(x.expires)L+=`; Expires=${x.expires.toUTCString()}`;if(x.path)L+=`; Path=${x.path}`;if(x.domain)L+=`; Domain=${x.domain}`;if(x.secure)L+="; Secure";if(x.httpOnly)L+="; HttpOnly";if(x.sameSite)L+=`; SameSite=${x.sameSite}`;return this.headers.append("Set-Cookie",L),this}get cookies(){if(!this.parsedCookies){let w=this.req.headers.get("cookie");this.parsedCookies=w?X(w):F}return this.parsedCookies}stream(w){let A=new Headers(this.headers??new Headers),x=new ReadableStream({async start(L){await w(L),L.close()}});return new Response(x,{headers:A})}yieldStream(w){return new Response}}function R(w,A){for(let x in A)w.set(x,A[x])}function U(w,A){for(let x in w)A[x]=w[x]}function X(w){return Object.fromEntries(w.split(";").map((A)=>{let[x,...L]=A.trim().split("=");return[x,decodeURIComponent(L.join("="))]}))}function N(w,A){let x={},[L]=A.split("?"),f=L.split("/").filter(Boolean),I=f.length-w.length;for(let z=0;z<w.length;z++)x[w[z]]=f[I+z];return x}function D(w,A){let x={},L=w.split("/"),[f]=A.split("?"),I=f.split("/");if(L.length!==I.length)return null;for(let z=0;z<L.length;z++){let K=L[z];if(K.charCodeAt(0)===58)x[K.slice(1)]=I[z]}return x}async function Z(w){let A=w.headers.get("Content-Type")||"";if(!A)return{};if(w.headers.get("Content-Length")==="0"||!w.body)return{};if(A.startsWith("application/json"))return await w.json();if(A.startsWith("application/x-www-form-urlencoded")){let L=await w.text();return Object.fromEntries(new URLSearchParams(L))}if(A.startsWith("multipart/form-data")){let L=await w.formData(),f={};for(let[I,z]of L.entries())f[I]=z;return f}return{error:"Unknown request body type"}}function Y(w,A){let x={},f=w?.split("?")[0]?.split("/").filter(Boolean);for(let I in A)x[I]=f?.[A[I]];return x}export{Y as parseParams,N as extractParam,D as extractDynamicParams,V as Context};
1
+ function z(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 R=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],N=Object.freeze({}),U="ALL";class I{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=N;urlObject=null;constructor(L,A,w,g,x,f){this.req=L,this.server=A,this.path=w,this.param=g,this.env=x,this.executionContext=f,this.headers=null}setHeader(L,A){if(!this.headers)this.headers=new Headers;return this.headers.set(L,A),this}removeHeader(L){if(this.headers)this.headers.delete(L);return this}set(L,A){if(this.contextData===N)this.contextData={};return this.contextData[L]=A,this}get(L){if(this.contextData===N)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):N;return this.parsedQuery}get params(){return this.param?this.param:N}get body(){if(this.req.method==="GET")return Promise.resolve(N);if(!this.parsedBody)this.parsedBody=(async()=>{try{let L=await K(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,A=200,w){if(!this.headers){if(!w)return new Response(L,{status:A,headers:{"Content-Type":"text/plain; charset=utf-8"}});let g={"Content-Type":"text/plain; charset=utf-8"};return G(w,g),new Response(L,{status:A,headers:g})}if(w)F(this.headers,w);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response(L,{status:A,headers:this.headers})}send(L,A=200,w){let g,x;if(L instanceof Uint8Array||L instanceof ArrayBuffer)g="application/octet-stream",x=L;else if(L!==null&&typeof L==="object")g="application/json; charset=utf-8",x=JSON.stringify(L);else if(typeof L==="string")g="text/plain; charset=utf-8",x=L;else g="text/plain; charset=utf-8",x=String(L);if(!this.headers){if(!w)return new Response(x,{status:A,headers:{"Content-Type":g}});let f={"Content-Type":g};return G(w,f),new Response(x,{status:A,headers:f})}if(w)F(this.headers,w);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",g);return new Response(x,{status:A,headers:this.headers})}json(L,A=200,w){if(!this.headers){if(!w)return Response.json(L,{status:A,headers:{"Content-Type":"application/json; charset=utf-8"}});let g={"Content-Type":"application/json; charset=utf-8"};return G(w,g),Response.json(L,{status:A,headers:g})}if(w)F(this.headers,w);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(L),{status:A,headers:this.headers})}file(L,A,w=200,g){let x=Bun.file(L);if(!this.headers){if(!g)return new Response(x,{status:w,headers:{"Content-Type":A??z(L)}});let f={"Content-Type":A??z(L)};return G(g,f),new Response(x,{status:w,headers:f})}if(g)F(this.headers,g);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",A??z(L));return new Response(x,{status:w,headers:this.headers})}async ejs(L,A={},w=200){console.log("this method is diabled now for some time")}redirect(L,A=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",L),new Response(null,{status:A,headers:this.headers})}setCookie(L,A,w={}){if(!this.headers)this.headers=new Headers;let g=`${encodeURIComponent(L)}=${encodeURIComponent(A)}`;if(w.maxAge)g+=`; Max-Age=${w.maxAge}`;if(w.expires)g+=`; Expires=${w.expires.toUTCString()}`;if(w.path)g+=`; Path=${w.path}`;if(w.domain)g+=`; Domain=${w.domain}`;if(w.secure)g+="; Secure";if(w.httpOnly)g+="; HttpOnly";if(w.sameSite)g+=`; SameSite=${w.sameSite}`;return this.headers.append("Set-Cookie",g),this}get cookies(){if(!this.parsedCookies){let L=this.req.headers.get("cookie");this.parsedCookies=L?E(L):N}return this.parsedCookies}stream(L){let A=new Headers(this.headers??new Headers),w=new ReadableStream({async start(g){await L(g),g.close()}});return new Response(w,{headers:A})}yieldStream(L){return new Response}}function F(L,A){for(let w in A)L.set(w,A[w])}function G(L,A){for(let w in L)A[w]=L[w]}function E(L){return Object.fromEntries(L.split(";").map((A)=>{let[w,...g]=A.trim().split("=");return[w,decodeURIComponent(g.join("="))]}))}async function K(L){let A=L.headers.get("Content-Type")||"";if(!A)return{};if(!L.body)return{};if(A.startsWith("application/json"))try{return await L.json()}catch(w){throw Error("Invalid request body format")}if(A.startsWith("application/x-www-form-urlencoded")){let w=await L.text();return Object.fromEntries(new URLSearchParams(w))}if(A.startsWith("multipart/form-data")){let w=await L.formData(),g={};for(let[x,f]of w.entries())g[x]=f;return g}return{error:"Unknown request body type"}}export{I as Context};
@@ -0,0 +1 @@
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};
package/dist/main.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CompileConfig, corsT, DieselFetchHandler, DieselOptions, errorFormat, FilterMethods, HookType, listenArgsT, middlewareFunc, RouteHandler, RouteNotFoundHandler, type handlerFunction, type Hooks, type HttpMethod } from "./types.js";
2
2
  import { Server } from "bun";
3
3
  import { AdvancedLoggerOptions, LoggerOptions } from "./middlewares/logger/logger.js";
4
- import { EventEmitter } from 'events';
4
+ import { EventEmitter } from "events";
5
5
  import { Context } from "./ctx.js";
6
6
  import { Router } from "./router/interface.js";
7
7
  export default class Diesel {
@@ -24,7 +24,7 @@ export default class Diesel {
24
24
  hasFilterEnabled: boolean;
25
25
  private serverInstance;
26
26
  staticFiles: any;
27
- user_jwt_secret: string;
27
+ user_jwt_secret: string | undefined;
28
28
  baseApiUrl: string;
29
29
  private enableFileRouter;
30
30
  idleTimeOut: number;
@@ -83,7 +83,6 @@ export default class Diesel {
83
83
  /**
84
84
  same as Route
85
85
  */
86
- register(module: (app: Diesel) => void): this;
87
86
  sub(prefix: string, router: Diesel): void;
88
87
  private addMiddlewareInRouter;
89
88
  private addRoute;
package/dist/main.js CHANGED
@@ -1,18 +1,18 @@
1
- var B={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"}},g=($,z,X)=>{let Z=B[$]||B.reset,Q=X?.method?B.method[X.method]||B.reset:B.reset,V=X?.status?X.status>=500?B.error:X.status>=400?B.warn:B.info:B.reset;console.log(`
2
- ${Z}[${$.toUpperCase()}]${B.reset} ${z} - ${Q}${X?.method||""}${B.reset}`);let G={timestamp:new Date().toISOString(),...X,status:X?.status?`${V}${X.status}${B.reset}`:void 0,method:X?.method?`${Q>Z}${X.method}${B.reset}`:void 0};console.log(JSON.stringify(G,null,2)+`
3
- `)},p=($)=>{let{app:z,logger:X,logLevel:Z="info",onRequest:Q,onSend:V,onError:G}=$||{};z?.addHooks("onRequest",(U)=>{U.req.startTime=Date.now(),X?.()??g(Z,"Incoming Request",{method:U.req.method,url:U.path,headers:{"user-agent":U.req.headers.get("user-agent"),"content-type":U.req.headers.get("content-type")}}),Q?.(U)}),z?.addHooks("onSend",async(U,W)=>{let F=`${Date.now()-U.req.startTime}ms`;X?.()??g(Z,"Response Sent",{method:U.req.method,url:U.url.toString(),status:W.status,duration:F,reqId:U.get?.("requestId"),headers:{"content-type":W.headers.get("content-type")}});let Y=await V?.(U);if(Y instanceof Response)return Y}),z?.addHooks("onError",async(U,W,F)=>{X?.()??g("error","Unhandled Error",{method:F.method,url:W,status:500,error:U.message});let Y=await G?.(U,W,F);if(Y instanceof Response)return Y})},v=($,z,X,Z=0,Q,V)=>{let G=B.method[z]||B.reset,U=Z>=500?B.error:Z>=400?B.warn:B.info,W=V?`[${V}] `:"",F=$==="<--"?`${$} ${G}${z}${B.reset} ${X} ${W}`:`${$} ${G}${z}${B.reset} ${X} ${U}${Z}${B.reset} ${Q??""} ${W}`;console.log(F)},F$=($)=>{let z=Date.now()-$;return z<1000?`${z}ms`:`${Math.round(z/1000)}s`},i=($)=>{let{app:z,log:X,onRequest:Z,onSend:Q,onError:V}=$;z.addHooks("onRequest",(G)=>{let{req:U,path:W}=G;U.startTime=Date.now(),X?.()??v("<--",U.method,W),Z?.(U,W)}),z.addHooks("onSend",async(G,U)=>{let{method:W,url:F}=G.req,Y=new URL(F).pathname,R=G.get?.("requestId");X?.()??v("-->",W,Y,U?.status,F$(G.req.startTime),R);let L=await Q?.(G);return L instanceof Response?L:U}),z.addHooks("onError",async(G,U,W)=>{let F=W.path;X?.()??v(G.message,W.method,F,500);let Y=await V?.(G,F,W);if(Y instanceof Response)return Y})};function l($,z){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(X)=>{try{let Z=X.cookies?.accessToken??X.req?.headers?.get("Authorization");if(!Z)return X.json({message:"Unauthorized",error:"No token provided"},401);if(Z.startsWith("Bearer "))Z=Z.slice(7);let Q=$?.verify(Z,z);if(!Q)return X.json({message:"Unauthorized",error:"Token could not be decoded"},401);X.set("user",Q)}catch(Z){let Q="Invalid token";if(Z.name==="TokenExpiredError")Q="Token expired";else if(Z.name==="JsonWebTokenError")Q="Malformed or tampered token";return X.json({message:"Unauthorized",error:Q},401)}}}function n($,z,X){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!z)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(Z)=>{try{let Q=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!Q)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(Q.startsWith("Bearer "))Q=Q.slice(7);let V=$?.verify(Q,X);if(!V)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let G=await z.findById(V._id).select("-password -refreshToken");if(!G)return Z.json({message:"Unauthorized: User not found"},404);Z.set("user",G);return}catch(Q){let V="Invalid token";if(Q.name==="TokenExpiredError")V="Token expired";else if(Q.name==="JsonWebTokenError")V="Malformed or tampered token";return Z.json({message:"Unauthorized",error:V},401)}}}function A($){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 s=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],D=Object.freeze({});class I{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=D;urlObject=null;constructor($,z,X,Z,Q,V){this.req=$,this.server=z,this.path=X,this.param=Z,this.env=Q,this.executionContext=V,this.headers=null}setHeader($,z){if(!this.headers)this.headers=new Headers;return this.headers.set($,z),this}removeHeader($){if(this.headers)this.headers.delete($);return this}set($,z){if(this.contextData===D)this.contextData={};return this.contextData[$]=z,this}get($){if(this.contextData===D)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):D;return this.parsedQuery}get params(){return this.param?this.param:D}get body(){if(this.req.method==="GET")return Promise.resolve(D);if(!this.parsedBody)this.parsedBody=(async()=>{try{let $=await Y$(this.req);if($.error)throw Error($.error);return Object.keys($).length===0?null:$}catch($){throw Error("Invalid request body format")}})();return this.parsedBody}text($,z=200,X){if(!this.headers){if(!X)return new Response($,{status:z,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Z={"Content-Type":"text/plain; charset=utf-8"};return E(X,Z),new Response($,{status:z,headers:Z})}if(X)H(this.headers,X);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response($,{status:z,headers:this.headers})}send($,z=200,X){let Z,Q;if($ instanceof Uint8Array||$ instanceof ArrayBuffer)Z="application/octet-stream",Q=$;else if($!==null&&typeof $==="object")Z="application/json; charset=utf-8",Q=JSON.stringify($);else if(typeof $==="string")Z="text/plain; charset=utf-8",Q=$;else Z="text/plain; charset=utf-8",Q=String($);if(!this.headers){if(!X)return new Response(Q,{status:z,headers:{"Content-Type":Z}});let V={"Content-Type":Z};return E(X,V),new Response(Q,{status:z,headers:V})}if(X)H(this.headers,X);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Z);return new Response(Q,{status:z,headers:this.headers})}json($,z=200,X){if(!this.headers){if(!X)return Response.json($,{status:z,headers:{"Content-Type":"application/json; charset=utf-8"}});let Z={"Content-Type":"application/json; charset=utf-8"};return E(X,Z),Response.json($,{status:z,headers:Z})}if(X)H(this.headers,X);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify($),{status:z,headers:this.headers})}file($,z,X=200,Z){let Q=Bun.file($);if(!this.headers){if(!Z)return new Response(Q,{status:X,headers:{"Content-Type":z??A($)}});let V={"Content-Type":z??A($)};return E(Z,V),new Response(Q,{status:X,headers:V})}if(Z)H(this.headers,Z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",z??A($));return new Response(Q,{status:X,headers:this.headers})}async ejs($,z={},X=200){console.log("this method is diabled now for some time")}redirect($,z=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",$),new Response(null,{status:z,headers:this.headers})}setCookie($,z,X={}){if(!this.headers)this.headers=new Headers;let Z=`${encodeURIComponent($)}=${encodeURIComponent(z)}`;if(X.maxAge)Z+=`; Max-Age=${X.maxAge}`;if(X.expires)Z+=`; Expires=${X.expires.toUTCString()}`;if(X.path)Z+=`; Path=${X.path}`;if(X.domain)Z+=`; Domain=${X.domain}`;if(X.secure)Z+="; Secure";if(X.httpOnly)Z+="; HttpOnly";if(X.sameSite)Z+=`; SameSite=${X.sameSite}`;return this.headers.append("Set-Cookie",Z),this}get cookies(){if(!this.parsedCookies){let $=this.req.headers.get("cookie");this.parsedCookies=$?J$($):D}return this.parsedCookies}stream($){let z=new Headers(this.headers??new Headers),X=new ReadableStream({async start(Z){await $(Z),Z.close()}});return new Response(X,{headers:z})}yieldStream($){return new Response}}function H($,z){for(let X in z)$.set(X,z[X])}function E($,z){for(let X in $)z[X]=$[X]}function J$($){return Object.fromEntries($.split(";").map((z)=>{let[X,...Z]=z.trim().split("=");return[X,decodeURIComponent(Z.join("="))]}))}async function Y$($){let z=$.headers.get("Content-Type")||"";if(!z)return{};if($.headers.get("Content-Length")==="0"||!$.body)return{};if(z.startsWith("application/json"))return await $.json();if(z.startsWith("application/x-www-form-urlencoded")){let Z=await $.text();return Object.fromEntries(new URLSearchParams(Z))}if(z.startsWith("multipart/form-data")){let Z=await $.formData(),Q={};for(let[V,G]of Z.entries())Q[V]=G;return Q}return{error:"Unknown request body type"}}var S=($)=>$!==null&&typeof $==="object"&&typeof $.then==="function",x=($)=>$!==null&&typeof $==="object"&&typeof $.status==="number"&&typeof $.headers==="object";async function C($,z,X){if(!z?.length)return;for(let Z=0;Z<z.length;Z++){let Q=z[Z](...X),V=Q instanceof Promise?await Q:Q;if(V&&$!=="onRequest")return V}}async function r($,z,X){for(let Z of $){let Q=await Z(z,X);if(Q)return Q}}async function a($,z,X){let Z=await B$($,z,X),Q=S(Z)?await Z:Z;if(Q)return Q}async function B$($,z,X){if(z.endsWith("/"))z=z.slice(0,-1);if(!$.filters.has(z))if($.filterFunction.length)for(let Z of $.filterFunction){let Q=await Z(X);if(Q)return Q}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function b($,z,X){if($.staticPath){let U=!0;if($.staticRequestPath)U=X.startsWith($.staticRequestPath);if(U){let W=await K$($,X,z);if(W)return W}}let V=($.router.find(z.req.method,"*")?.handler).slice(-1);if(V.length>0){let U=await V[0](z);if(x(U))return U}let G=await Promise.resolve($.routeNotFoundFunc(z));return x(G)?G:y(404,`404 Route not found for ${X}`)}function y($,z){return new Response(JSON.stringify({error:z}),{status:$,headers:{"Content-Type":"application/json"}})}async function K$($,z,X){if(!$.staticPath)return null;let Z=`${$.staticPath}${z}`;if(await Bun.file(Z).exists()){let V=A(Z);return X.file(Z,V,200)}return null}var c=($)=>$.constructor.name==="AsyncFunction",t=($,z,X,...Z)=>{if(z.length>5)$.push(`
4
- for (let i = 0; i < diesel.hooks.${X}.length; i++) {
5
- const result = diesel.hooks.${X}[i](${Z});
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(`
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(`
4
+ for (let i = 0; i < diesel.hooks.${z}.length; i++) {
5
+ const result = diesel.hooks.${z}[i](${Z});
6
6
  const finalResult = result instanceof Promise ? await result : result;
7
- if (finalResult && '${X}' !== 'onRequest') return finalResult
7
+ if (finalResult && '${z}' !== 'onRequest') return finalResult
8
8
  }
9
- `);else z?.forEach((Q,V)=>{if(c(Q))$.push(`
10
- const ${X}${V}Result = await diesel.hooks.${X}[${V}](${Z})
11
- if (${X}${V}Result && '${X}' !== 'onRequest') return ${X}${V}Result
9
+ `);else L?.forEach((X,G)=>{if(H(X))$.push(`
10
+ const ${z}${G}Result = await diesel.hooks.${z}[${G}](${Z})
11
+ if (${z}${G}Result && '${z}' !== 'onRequest') return ${z}${G}Result
12
12
  `);else $.push(`
13
- const ${X}${V}Result = diesel.hooks.${X}[${V}](${Z})
14
- if (${X}${V}Result && '${X}' !== 'onRequest') return ${X}${V}Result
15
- `)})},D$=($)=>{$.push(`
13
+ const ${z}${G}Result = diesel.hooks.${z}[${G}](${Z})
14
+ if (${z}${G}Result && '${z}' !== 'onRequest') return ${z}${G}Result
15
+ `)})},L$=($)=>{$.push(`
16
16
  let pathname;
17
17
  const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
18
18
  let i = start;
@@ -30,9 +30,9 @@ ${Z}[${$.toUpperCase()}]${B.reset} ${z} - ${Q}${X?.method||""}${B.reset}`);let G
30
30
  if (!pathname) {
31
31
  pathname = req.url.slice(start, i);
32
32
  }
33
- `)};var u=($)=>{let z=[],X=$?.hasPreHandlerHook?$.hooks.preHandler:[],Z=$?.hasOnSendHook?$.hooks.onSend:[];if(D$(z),z.push(`
33
+ `)};var b=($)=>{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
- `),z.push(`
35
+ `),L.push(`
36
36
  const ctx = new Context(
37
37
  req,
38
38
  server,
@@ -41,10 +41,10 @@ ${Z}[${$.toUpperCase()}]${B.reset} ${z} - ${Q}${X?.method||""}${B.reset}`);let G
41
41
  env,
42
42
  executionContext
43
43
  )
44
- `),$.hasFilterEnabled)z.push(`
44
+ `),$.hasFilterEnabled)L.push(`
45
45
  const filterResponse = await runFilter(diesel, pathname, ctx);
46
46
  if (filterResponse) return filterResponse;
47
- `);if($.hasPreHandlerHook)t(z,X,"preHandler","ctx");if(z.push(`
47
+ `);if($.hasPreHandlerHook)p(L,z,"preHandler","ctx");if(L.push(`
48
48
  let finalResult
49
49
  const handlers = matchedRouteHandler?.handler;
50
50
 
@@ -59,53 +59,54 @@ ${Z}[${$.toUpperCase()}]${B.reset} ${z} - ${Q}${X?.method||""}${B.reset}`);let G
59
59
  if (finalResult) break;
60
60
  }
61
61
  }
62
- `),$.hasOnSendHook)t(z,Z,"onSend","ctx","finalResult");z.push(`
62
+ `),$.hasOnSendHook)p(L,Z,"onSend","ctx","finalResult");L.push(`
63
63
  if (finalResult) return finalResult;
64
- `),z.push(`
64
+ `),L.push(`
65
65
  return await handleRouteNotFound(diesel, ctx, pathname);
66
- `);let Q=`
66
+ `);let X=`
67
67
  return async function pipeline(req, diesel, server, env, executionContext) {
68
- ${z.join(`
68
+ ${L.join(`
69
69
  `)}
70
70
  }
71
- `;return Function("runFilter","handleRouteNotFound","generateErrorResponse","Context","isPromise",Q)(a,b,y,I,S)},e=($,z,X,...Z)=>{let Q=[],V;if(typeof Z[0]==="string"||typeof Z[0]==="object")V=Z[0];let G=Z,U=$?.hasOnReqHook?$.hooks.onRequest:[],W=$.filters.has(X),F=$.filterFunction;if(U&&U?.length>0)Q.push(`
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(`
72
72
  const onRequestResult = await runHooks(
73
73
  "onRequest",
74
74
  onRequestHooks,
75
- [req, "${X}", server]
75
+ [req, "${z}", server]
76
76
  );
77
77
  if (onRequestResult) return onRequestResult;
78
- `);if($.hasFilterEnabled){if(!W)Q.push(`if (${F.length}) {
78
+ `);if($.hasFilterEnabled){if(!Q)X.push(`if (${N.length}) {
79
79
  for (const filterFunction of filterFunctions) {
80
80
  const filterResult = await filterFunction(req, server);
81
81
  if (filterResult) return filterResult;
82
82
  }
83
83
  } else {
84
84
  return Response.json({ error: "Protected route, authentication required" }, { status: 401 });
85
- }`)}if(Q.push(`
86
- if ("${z}" !== req.method)
85
+ }`)}if(X.push(`
86
+ if ("${L}" !== req.method)
87
87
  return new Response("Method Not Allowed", { status: 405 });
88
- `),typeof V<"u")if(typeof V==="string")Q.push(`
89
- return new Response(${JSON.stringify(V)});
90
- `);else{let L=JSON.stringify(V);Q.push(`
91
- return new Response(${JSON.stringify(L)}, {
88
+ `),typeof G<"u")if(typeof G==="string")X.push(`
89
+ return new Response(${JSON.stringify(G)});
90
+ `);else{let U=JSON.stringify(G);X.push(`
91
+ return new Response(${JSON.stringify(U)}, {
92
92
  headers: { "content-type": "application/json; charset=utf-8" }
93
93
  });
94
- `)}else if(G.length===1){let L=G[0];if(c(L))Q.push(`
94
+ `)}else if(V.length===1){let U=V[0];if(H(U))X.push(`
95
95
  const response = await handlers[0](req, server);
96
96
  if (response instanceof Response) return response;
97
- `);else Q.push(`
97
+ `);else X.push(`
98
98
  const response = handlers[0](req, server);
99
99
  if (response instanceof Response) return response;
100
- `)}else G.forEach((L,K)=>{if(c(L))Q.push(`
101
- const response${K} = await handlers[${K}](req, server);
102
- if (response${K} instanceof Response) return response${K};
103
- `);else Q.push(`
104
- const response${K} = handlers[${K}](req, server);
105
- if (response${K} instanceof Response) return response${K};
106
- `)});let Y=`
100
+ `)}else V.forEach((U,Y)=>{if(H(U))X.push(`
101
+ const response${Y} = await handlers[${Y}](req, server);
102
+ if (response${Y} instanceof Response) return response${Y};
103
+ `);else X.push(`
104
+ const response${Y} = handlers[${Y}](req, server);
105
+ if (response${Y} instanceof Response) return response${Y};
106
+ `)});let F=`
107
107
  return async function(req, server) {
108
- ${Q.join(`
108
+ ${X.join(`
109
109
  `)}
110
110
  }
111
- `;return Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",Y)(r,G,C,F,U)};var L$=($,z)=>{try{return z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(X)=>{try{return z(X)}catch{return X}})}},N$=($)=>L$($,decodeURI),P=($)=>{let z=$.indexOf("/",$.indexOf(":")+4),X=z;for(;X<$.length;X++){let Z=$.charCodeAt(X);if(Z===37){let Q=$.indexOf("?",X),V=$.slice(z,Q===-1?void 0:Q);return N$(V.includes("%25")?V.replace(/%25/g,"%2525"):V)}else if(Z===63)break}return $.slice(z,X)};var h=Symbol.for,O=Symbol("kCapture"),Z$=h("events.errorMonitor"),S$=Symbol("events.maxEventTargetListeners"),C$=Symbol("events.maxEventTargetListenersWarned"),$$=h("nodejs.rejection"),O$=h("nodejs.rejection"),z$=Array.prototype.slice,w=10,N=function($){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[O]=$?.captureRejections?Boolean($?.captureRejections):J[O])this.emit=M$},J=N.prototype={};J._events=void 0;J._eventsCount=0;J._maxListeners=void 0;J.setMaxListeners=function($){return d($,"setMaxListeners",0),this._maxListeners=$,this};J.constructor=N;J.getMaxListeners=function(){return this?._maxListeners??w};function Q$($,z){var{_events:X}=$;if(z[0]??=Error("Unhandled error."),!X)throw z[0];var Z=X[Z$];if(Z)for(var Q of z$.call(Z))Q.apply($,z);var V=X.error;if(!V)throw z[0];for(var Q of z$.call(V))Q.apply($,z);return!0}function w$($,z,X,Z){z.then(void 0,function(Q){queueMicrotask(()=>A$($,Q,X,Z))})}function A$($,z,X,Z){if(typeof $[$$]==="function")$[$$](z,X,...Z);else try{$[O]=!1,$.emit("error",z)}finally{$[O]=!0}}var q$=function($,...z){if($==="error")return Q$(this,z);var{_events:X}=this;if(X===void 0)return!1;var Z=X[$];if(Z===void 0)return!1;let Q=Z.length>1?Z.slice():Z;for(let V=0,{length:G}=Q;V<G;V++){let U=Q[V];switch(z.length){case 0:U.call(this);break;case 1:U.call(this,z[0]);break;case 2:U.call(this,z[0],z[1]);break;case 3:U.call(this,z[0],z[1],z[2]);break;default:U.apply(this,z);break}}return!0},M$=function($,...z){if($==="error")return Q$(this,z);var{_events:X}=this;if(X===void 0)return!1;var Z=X[$];if(Z===void 0)return!1;let Q=Z.length>1?Z.slice():Z;for(let V=0,{length:G}=Q;V<G;V++){let U=Q[V],W;switch(z.length){case 0:W=U.call(this);break;case 1:W=U.call(this,z[0]);break;case 2:W=U.call(this,z[0],z[1]);break;case 3:W=U.call(this,z[0],z[1],z[2]);break;default:W=U.apply(this,z);break}if(W!==void 0&&typeof W?.then==="function"&&W.then===Promise.prototype.then)w$(this,W,$,z)}return!0};J.emit=q$;J.addListener=function($,z){_(z);var X=this._events;if(!X)X=this._events={__proto__:null},this._eventsCount=0;else if(X.newListener)this.emit("newListener",$,z.listener??z);var Z=X[$];if(!Z)X[$]=[z],this._eventsCount++;else{Z.push(z);var Q=this._maxListeners??w;if(Q>0&&Z.length>Q&&!Z.warned)V$(this,$,Z)}return this};J.on=J.addListener;J.prependListener=function($,z){_(z);var X=this._events;if(!X)X=this._events={__proto__:null},this._eventsCount=0;else if(X.newListener)this.emit("newListener",$,z.listener??z);var Z=X[$];if(!Z)X[$]=[z],this._eventsCount++;else{Z.unshift(z);var Q=this._maxListeners??w;if(Q>0&&Z.length>Q&&!Z.warned)V$(this,$,Z)}return this};function V$($,z,X){X.warned=!0;let Z=Error(`Possible EventEmitter memory leak detected. ${X.length} ${String(z)} listeners added to [${$.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);Z.name="MaxListenersExceededWarning",Z.emitter=$,Z.type=z,Z.count=X.length,console.warn(Z)}function G$($,z,...X){this.removeListener($,z),z.apply(this,X)}J.once=function($,z){_(z);let X=G$.bind(this,$,z);return X.listener=z,this.addListener($,X),this};J.prependOnceListener=function($,z){_(z);let X=G$.bind(this,$,z);return X.listener=z,this.prependListener($,X),this};J.removeListener=function($,z){_(z);var{_events:X}=this;if(!X)return this;var Z=X[$];if(!Z)return this;var Q=Z.length;let V=-1;for(let G=Q-1;G>=0;G--)if(Z[G]===z||Z[G].listener===z){V=G;break}if(V<0)return this;if(V===0)Z.shift();else Z.splice(V,1);if(Z.length===0)delete X[$],this._eventsCount--;return this};J.off=J.removeListener;J.removeAllListeners=function($){var{_events:z}=this;if($&&z){if(z[$])delete z[$],this._eventsCount--}else this._events={__proto__:null};return this};J.listeners=function($){var{_events:z}=this;if(!z)return[];var X=z[$];if(!X)return[];return X.map((Z)=>Z.listener??Z)};J.rawListeners=function($){var{_events:z}=this;if(!z)return[];var X=z[$];if(!X)return[];return X.slice()};J.listenerCount=function($){var{_events:z}=this;if(!z)return 0;return z[$]?.length??0};J.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};J[O]=!1;function I$($,z,X){var Z=X?.signal;if(U$(Z,"options.signal"),Z?.aborted)throw new m(void 0,{cause:Z?.reason});let{resolve:Q,reject:V,promise:G}=$newPromiseCapability(Promise),U=(Y)=>{if($.removeListener(z,W),Z!=null)f(Z,"abort",F);V(Y)},W=(...Y)=>{if(typeof $.removeListener==="function")$.removeListener("error",U);if(Z!=null)f(Z,"abort",F);Q(Y)};if(X$($,z,W,{once:!0}),z!=="error"&&typeof $.once==="function")$.once("error",U);function F(){f($,z,W),f($,"error",U),V(new m(void 0,{cause:Z?.reason}))}if(Z!=null)X$(Z,"abort",F,{once:!0});return G}function _$($,z){return $.listeners(z)}function j$($,...z){d($,"setMaxListeners",0);var X;if(z&&(X=z.length))for(let Z=0;Z<X;Z++)z[Z].setMaxListeners($);else w=$}function R$($,z){return $.listenerCount(z)}function f($,z,X,Z){if(typeof $.removeListener==="function")$.removeListener(z,X);else $.removeEventListener(z,X,Z)}function X$($,z,X,Z){if(typeof $.on==="function")if(Z.once)$.once(z,X);else $.on(z,X);else $.addEventListener(z,X,Z)}class m extends Error{constructor($="The operation was aborted",z=void 0){if(z!==void 0&&typeof z!=="object")throw q("options","Object",z);super($,z);this.code="ABORT_ERR",this.name="AbortError"}}function q($,z,X){let Z=TypeError(`The "${$}" argument must be of type ${z}. Received ${X}`);return Z.code="ERR_INVALID_ARG_TYPE",Z}function T$($,z,X){let Z=RangeError(`The "${$}" argument is out of range. It must be ${z}. Received ${X}`);return Z.code="ERR_OUT_OF_RANGE",Z}function U$($,z){if($!==void 0&&($===null||typeof $!=="object"||!("aborted"in $)))throw q(z,"AbortSignal",$)}function d($,z,X,Z){if(typeof $!=="number")throw q(z,"number",$);if(X!=null&&$<X||Z!=null&&$>Z||(X!=null||Z!=null)&&Number.isNaN($))throw T$(z,`${X!=null?`>= ${X}`:""}${X!=null&&Z!=null?" && ":""}${Z!=null?`<= ${Z}`:""}`,$)}function _($){if(typeof $!=="function")throw TypeError("The listener must be a function")}function H$($,z){if(typeof $!=="boolean")throw q(z,"boolean",$)}function E$($){return $?._maxListeners??w}function b$($,z){if($===void 0)throw q("signal","AbortSignal",$);if(U$($,"signal"),typeof z!=="function")throw q("listener","function",z);let X;if($.aborted)queueMicrotask(()=>z());else $.addEventListener("abort",z,{__proto__:null,once:!0}),X=()=>{$.removeEventListener("abort",z)};return{__proto__:null,[Symbol.dispose](){X?.()}}}Object.defineProperties(N,{captureRejections:{get(){return J[O]},set($){H$($,"EventEmitter.captureRejections"),J[O]=$},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return w},set:($)=>{d($,"defaultMaxListeners",0),w=$}},kMaxEventTargetListeners:{value:S$,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:C$,enumerable:!1,configurable:!1,writable:!1}});Object.assign(N,{once:I$,getEventListeners:_$,getMaxListeners:E$,setMaxListeners:j$,EventEmitter:N,usingDomains:!1,captureRejectionSymbol:O$,errorMonitor:Z$,addAbortListener:b$,init:N,listenerCount:R$});class k{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class j{root;globalMiddlewares;constructor(){this.root=new k,this.globalMiddlewares=[]}pushMiddleware($,z){if(!Array.isArray(z))z=[z];if($==="/"){this.globalMiddlewares.push(...z);return}let X=this.root,Z=$.split("/").filter(Boolean);for(let Q of Z){let V=Q;if(Q.startsWith(":"))V=":";else if(Q.startsWith("*"))X.middlewares.push(...z);if(!X.children[V])X.children[V]=new k;X=X.children[V]}X.middlewares.push(...z)}addMiddleware($,z){return this.pushMiddleware($,z)}insert($,z,X){let Z=this.root;if(z==="/"){Z.handlers[$]=X,Z.params=D;return}let Q=z.split("/").filter(Boolean),V={};for(let G=0;G<Q.length;G++){let U=Q[G],W=U,F="";if(U.startsWith(":"))W=":",F=U.slice(1);if(!Z.children[W])Z.children[W]=new k;if(Z=Z.children[W],F)V[F]=G,Z.paramName=F}Z.params=V,Z.handlers[$]=X}add($,z,X){return this.insert($,z,X)}search($,z){let X=this.root,Z=z.split("/"),Q=this.globalMiddlewares.slice(),V;for(let G=0;G<Z.length;G++){let U=Z[G];if(U.length===0)continue;if(X.children[U])X=X.children[U];else if(X.children[":"]){if(X=X.children[":"],!V)V={};V[X.paramName]=U}else if(X.children["*"]){X=X.children["*"];break}else return{params:V,handler:Q};if(X.middlewares.length>0){let W=X.middlewares;for(let F=0;F<W.length;F++)Q.push(W[F])}}if(X.handlers[$])Q.push(X.handlers[$]);if(X.handlers.ALL)Q.push(X.handlers.ALL);return{params:V,handler:Q}}find($,z){return this.search($,z)}}class o{static create($){switch($){case"t2":return new j;case"trie":return new j;default:return new j}}}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($={}){s.forEach((K)=>{this[K.toLocaleLowerCase()]=(T,...W$)=>{return this.addRoute(K,T,W$),this}});let{router:z="t2",routerInstance:X,errorFormat:Z="json",platform:Q="bun",enableFileRouting:V=!1,prefixApiUrl:G="",baseApiUrl:U="",jwtSecret:W,idleTimeOut:F=10,pipelineArchitecture:Y=!1,logger:R,onError:L}=$;if(X)this.router=X;else this.router=o.create(z);if(this.errorFormat=Z,this.platform=Q,!M.instance)M.instance=this;if(Y)this.#$=!0;if(this.errorFormat=Z,this.emitter=new N,this.prefixApiUrl=G??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=F??10,this.enableFileRouter=V??!1,this.baseApiUrl=U||"",this.user_jwt_secret=W||process.env.DIESEL_JWT_SECRET||"default_diesel_secret_for_jwt",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:[]},L)this.addHooks("onError",(K,T)=>{console.log("Got an exception:",K),console.log("Request Path:",T)});if(R)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(z,X,Z){return(Q,V)=>{let G=V,U="";if(typeof Q==="string")U=Q;else if(typeof Q==="function")G=Q;else if(typeof Q!=="string")U="";let W=$+U;return z[X](W,G)}}})}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 z=async(X,Z)=>{let Q=X.path;for(let V of this.filters)if(Q.startsWith(V))return;for(let V of $){let G=await V(X,Z);if(G)return G}};this.router.addMiddleware("/",[z])}},authenticateJwt:($)=>{let z=async(X)=>{let Z=X.path;for(let V of this.filters)if(Z.startsWith(V))return;let Q=l($,this.user_jwt_secret)(X);if(Q)return Q};this.router.addMiddleware("/",z)},authenticateJwtDB:($,z)=>{let X=async(Z)=>{let Q=Z.path;for(let G of this.filters)if(Q.startsWith(G))return;let V=n($,z,this.user_jwt_secret)(Z);if(V)return V};this.router.addMiddleware("/",X)}}}redirect($,z,X){return this.any($,(Z)=>{let Q=Z.params,V=z;if(Q)for(let U in Q)V=V.replace(`:${U}`,Q[U]);let G=Z.url.search;if(G)V+=G;return Z.redirect(V,X)}),this}static($,z){return this.staticPath=$,this.staticRequestPath=z,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,z){if(typeof $!=="string")throw Error("hookName must be a string");if(typeof z!=="function")throw Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(z),this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler?.push(z),this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler?.push(z),this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend?.push(z),this.hasOnSendHook=!0;break;case"onError":this.hooks.onError?.push(z),this.hasOnError=!0;break;case"onClose":this.hooks.onClose?.push(z);break;default:throw Error(`Unknown hook type: ${$}`)}return this}useLogger($){return i($),this}useAdvancedLogger($){return p($),this}BunRoute($,z,...X){if(!z||typeof z!=="string")throw Error("give a path in string format");let Z=e(this,$.toUpperCase(),z,...X);return this.routes[z]=Z,this}listen($,...z){let X="0.0.0.0",Z=void 0,Q={};for(let G of z)if(typeof G==="string")X=G;else if(typeof G==="function")Z=G;else if(typeof G==="object"&&G!==null)Q=G;let V={port:$,hostname:X,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)V.routes=this.routes;if(Q.cert&&Q.key)V.certFile=Q.cert,V.keyFile=Q.key;return this.serverInstance=Bun?.serve(V),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,($,z,X)=>{return this.#z($,void 0,z,X)}}fetch(){if(this.tempRoutes=null,this.tempMiddlewares=null,this.platform==="cf"||this.platform==="cloudflare"){if(this.#$){let $=u(this);return(z,X,Z)=>{return $(z,this,void 0,X,Z).catch(async(Q)=>{return this.handleError(Q,P(z.url),z)})}}return($,z,X)=>{return this.#z($,void 0,z,X)}}if(this.#$){let $=u(this);return(z,X)=>{return $(z,this,X,void 0,void 0).catch(async(Z)=>{return this.handleError(Z,P(z.url),z)})}}return this.#z.bind(this)}async#z($,z,X,Z){let Q=P($.url),V=this.router.find($.method,Q),G=new I($,z,Q,V?.params||D,X,Z);try{if(this.hasOnReqHook)await C("onRequest",this.hooks.onRequest,[G]);if(this.hasPreHandlerHook){let F=await C("preHandler",this.hooks.preHandler,[G]);if(F)return F}let U,W=V?.handler;if(W.length===1){let F=W[0](G);U=S(F)?await F:F}else for(let F=0;F<W.length;F++){let Y=W[F](G);if(U=S(Y)?await Y:Y,U)break}if(this.hasOnSendHook){let F=await C("onSend",this.hooks.onSend,[G,U]);if(F)return F}if(U)return U;return await b(this,G,Q)}catch(U){return this.handleError(U,Q,$)}}async handleError($,z,X){let Q=this.errorFormat,V=await C("onError",this.hooks.onError,[$,z,X]);if(V)return V;if($&&typeof $==="object"&&$.name==="HTTPException"){let W=$;if(console.error(`HTTPException on path: ${z}`,{status:W.status,message:W.message,cause:W.cause,res:W.res,stack:W.stack}),W.res)return W.res;return Q==="json"?Response.json({error:W.message},{status:W.status}):new Response(W.message,{status:W.status})}let G=$ instanceof Error?$.message:"Internal Server Error",U=$ instanceof Error?$.stack:void 0;if(console.error(`Error on path: ${z}`,{message:G,stack:U}),Q==="json"){let W={error:G,...!1,path:z};return Response.json(W,{status:500,headers:{"Content-Type":"application/json"}})}else{let W=`Error: ${G}`;return new Response(W,{headers:{"Content-Type":"text/plain"},status:500})}}mount($,z){let X=typeof z==="function"?z:z.fetch(),Z=$.endsWith("/*")?$.slice(0,-1):$,Q=Z==="/"?0:Z.length;this.all($,(V)=>{let G=new URL(V.req.url);G.pathname=G.pathname.slice(Q)||"/";let U=new Request(G,V.req);return X(U,V.server,V.env,V.executionContext)})}route($,z){$=$&&$.length>0?$:z?.prefixApiUrl;let X=z?.tempRoutes??new Map;for(let[Z,Q]of X.entries()){let V=Z.replace(/::\w+$/,""),G=`${$}${V}`,U=Q.handlers.slice(0,-1);this.router.addMiddleware(G,U);let W=Q.handlers[Q.handlers.length-1],F=Q.method;try{this.router.add(F,G,W)}catch(Y){console.error(`Error inserting ${G}:`,Y)}}for(let[Z,Q]of z?.tempMiddlewares?.entries()){let V=Z==="/"?$||"/":`${$}${Z}`;this.router.addMiddleware(V,Q)}return z=null,this}register($){let z=new M,X=()=>{};return this}sub($,z){return this.mount($,z)}addMiddlewareInRouter($,z){this.router.addMiddleware($,z)}addRoute($,z,X){if(typeof z!=="string")throw Error(`Error in ${X[X.length-1]}: Path must be a string. Received: ${typeof z}`);if(typeof $!=="string")throw Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(z+"::"+$,{method:$,handlers:X});let Z=X.slice(0,-1),Q=X[X.length-1];if(Z.length>0)this.addMiddlewareInRouter(z,Z);try{$=$==="ANY"?"ALL":$,this.router.add($,z,Q)}catch(V){console.error(`Error inserting ${z}:`,V)}}use($,...z){if(typeof $==="string"){let X=$==="/"?"/":$;if(!this.tempMiddlewares?.has(X))this.tempMiddlewares?.set(X,[]);this.tempMiddlewares?.get(X).push(...z),this.router.addMiddleware(X,z)}else if(typeof $==="function"){let X=[$,...z];if(!this.tempMiddlewares?.has("/"))this.tempMiddlewares?.set("/",[]);this.tempMiddlewares?.get("/").push(...z),this.router.addMiddleware("/",X)}return this}routeNotFound($){return this.routeNotFoundFunc=$,this}onMethod($,z,...X){let Z=Array.isArray($)?$:[$];for(let Q of Z){let V=Q.toLowerCase();if(V in this)this[V](z,...X);else this.addRoute(Q.toUpperCase(),z,X)}return this}on($,z){return this.emitter.on($,z),this}emit($,...z){return this.emitter.emit($,...z),this}}export{M as default};
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};
@@ -0,0 +1 @@
1
+ import C from"path";import D from"fs";async function E(v,z,k,A){let q=await import(z),c;if(A===".ts")c=C.basename(z,".ts");else if(A===".js")c=C.basename(z,".js");let j=k+"/"+c;if(j.endsWith("/index"))j=k;else if(j.endsWith("/api"))j=k;j=j.replace(/\[(.*?)\]/g,":$1");let G=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let B of G)if(q[B]){let H=B.toLowerCase(),I=q[B];v[H](`${v.baseApiUrl}${j}`,I)}}async function J(v,z,k){let A=await D.promises.readdir(z);for(let q of A){let c=C.join(z,q);if((await D.promises.stat(c)).isDirectory())await J(v,c,k+"/"+q);else if(q.endsWith(".ts"))await E(v,c,k,".ts");else if(q.endsWith(".js"))await E(v,c,k,".js")}}export{E as registerFileRoutes,J as loadRoutes};
@@ -1 +1 @@
1
- function g(e){if(typeof e!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(e))}function x(e,r){var n="",i=0,l=-1,t=0,f;for(var o=0;o<=e.length;++o){if(o<e.length)f=e.charCodeAt(o);else if(f===47)break;else f=47;if(f===47){if(l===o-1||t===1);else if(l!==o-1&&t===2){if(n.length<2||i!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var a=n.lastIndexOf("/");if(a!==n.length-1){if(a===-1)n="",i=0;else n=n.slice(0,a),i=n.length-1-n.lastIndexOf("/");l=o,t=0;continue}}else if(n.length===2||n.length===1){n="",i=0,l=o,t=0;continue}}if(r){if(n.length>0)n+="/..";else n="..";i=2}}else{if(n.length>0)n+="/"+e.slice(l+1,o);else n=e.slice(l+1,o);i=o-l-1}l=o,t=0}else if(f===46&&t!==-1)++t;else t=-1}return n}function T(e,r){var n=r.dir||r.root,i=r.base||(r.name||"")+(r.ext||"");if(!n)return i;if(n===r.root)return n+i;return n+e+i}function A(){var e="",r=!1,n;for(var i=arguments.length-1;i>=-1&&!r;i--){var l;if(i>=0)l=arguments[i];else{if(n===void 0)n=process.cwd();l=n}if(g(l),l.length===0)continue;e=l+"/"+e,r=l.charCodeAt(0)===47}if(e=x(e,!r),r)if(e.length>0)return"/"+e;else return"/";else if(e.length>0)return e;else return"."}function k(e){if(g(e),e.length===0)return".";var r=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;if(e=x(e,!r),e.length===0&&!r)e=".";if(e.length>0&&n)e+="/";if(r)return"/"+e;return e}function E(e){return g(e),e.length>0&&e.charCodeAt(0)===47}function V(){if(arguments.length===0)return".";var e;for(var r=0;r<arguments.length;++r){var n=arguments[r];if(g(n),n.length>0)if(e===void 0)e=n;else e+="/"+n}if(e===void 0)return".";return k(e)}function I(e,r){if(g(e),g(r),e===r)return"";if(e=A(e),r=A(r),e===r)return"";var n=1;for(;n<e.length;++n)if(e.charCodeAt(n)!==47)break;var i=e.length,l=i-n,t=1;for(;t<r.length;++t)if(r.charCodeAt(t)!==47)break;var f=r.length,o=f-t,a=l<o?l:o,d=-1,s=0;for(;s<=a;++s){if(s===a){if(o>a){if(r.charCodeAt(t+s)===47)return r.slice(t+s+1);else if(s===0)return r.slice(t+s)}else if(l>a){if(e.charCodeAt(n+s)===47)d=s;else if(s===0)d=0}break}var S=e.charCodeAt(n+s),R=r.charCodeAt(t+s);if(S!==R)break;else if(S===47)d=s}var c="";for(s=n+d+1;s<=i;++s)if(s===i||e.charCodeAt(s)===47)if(c.length===0)c+="..";else c+="/..";if(c.length>0)return c+r.slice(t+d);else{if(t+=d,r.charCodeAt(t)===47)++t;return r.slice(t)}}function L(e){return e}function P(e){if(g(e),e.length===0)return".";var r=e.charCodeAt(0),n=r===47,i=-1,l=!0;for(var t=e.length-1;t>=1;--t)if(r=e.charCodeAt(t),r===47){if(!l){i=t;break}}else l=!1;if(i===-1)return n?"/":".";if(n&&i===1)return"//";return e.slice(0,i)}function z(e,r){if(r!==void 0&&typeof r!=="string")throw TypeError('"ext" argument must be a string');g(e);var n=0,i=-1,l=!0,t;if(r!==void 0&&r.length>0&&r.length<=e.length){if(r.length===e.length&&r===e)return"";var f=r.length-1,o=-1;for(t=e.length-1;t>=0;--t){var a=e.charCodeAt(t);if(a===47){if(!l){n=t+1;break}}else{if(o===-1)l=!1,o=t+1;if(f>=0)if(a===r.charCodeAt(f)){if(--f===-1)i=t}else f=-1,i=o}}if(n===i)i=o;else if(i===-1)i=e.length;return e.slice(n,i)}else{for(t=e.length-1;t>=0;--t)if(e.charCodeAt(t)===47){if(!l){n=t+1;break}}else if(i===-1)l=!1,i=t+1;if(i===-1)return"";return e.slice(n,i)}}function $(e){g(e);var r=-1,n=0,i=-1,l=!0,t=0;for(var f=e.length-1;f>=0;--f){var o=e.charCodeAt(f);if(o===47){if(!l){n=f+1;break}continue}if(i===-1)l=!1,i=f+1;if(o===46){if(r===-1)r=f;else if(t!==1)t=1}else if(r!==-1)t=-1}if(r===-1||i===-1||t===0||t===1&&r===i-1&&r===n+1)return"";return e.slice(r,i)}function H(e){if(e===null||typeof e!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return T("/",e)}function J(e){g(e);var r={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return r;var n=e.charCodeAt(0),i=n===47,l;if(i)r.root="/",l=1;else l=0;var t=-1,f=0,o=-1,a=!0,d=e.length-1,s=0;for(;d>=l;--d){if(n=e.charCodeAt(d),n===47){if(!a){f=d+1;break}continue}if(o===-1)a=!1,o=d+1;if(n===46){if(t===-1)t=d;else if(s!==1)s=1}else if(t!==-1)s=-1}if(t===-1||o===-1||s===0||s===1&&t===o-1&&t===f+1){if(o!==-1)if(f===0&&i)r.base=r.name=e.slice(1,o);else r.base=r.name=e.slice(f,o)}else{if(f===0&&i)r.name=e.slice(1,t),r.base=e.slice(1,o);else r.name=e.slice(f,t),r.base=e.slice(f,o);r.ext=e.slice(t,o)}if(f>0)r.dir=e.slice(0,f-1);else if(i)r.dir="/";return r}var M="/",X=":",q=((e)=>(e.posix=e,e))({resolve:A,normalize:k,isAbsolute:E,join:V,relative:I,_makeLong:L,dirname:P,basename:z,extname:$,format:H,parse:J,sep:M,delimiter:X,win32:null,posix:null}),m=q;var F=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),y={randomUUID:F};var b,G=new Uint8Array(16);function C(){if(!b){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");b=crypto.getRandomValues.bind(crypto)}return b(G)}var u=[];for(let e=0;e<256;++e)u.push((e+256).toString(16).slice(1));function U(e,r=0){return(u[e[r+0]]+u[e[r+1]]+u[e[r+2]]+u[e[r+3]]+"-"+u[e[r+4]]+u[e[r+5]]+"-"+u[e[r+6]]+u[e[r+7]]+"-"+u[e[r+8]]+u[e[r+9]]+"-"+u[e[r+10]]+u[e[r+11]]+u[e[r+12]]+u[e[r+13]]+u[e[r+14]]+u[e[r+15]]).toLowerCase()}function K(e,r,n){if(y.randomUUID&&!r&&!e)return y.randomUUID();e=e||{};let i=e.random??e.rng?.()??C();if(i.length<16)throw Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,r){if(n=n||0,n<0||n+16>r.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let l=0;l<16;++l)r[n+l]=i[l];return r}return U(i)}var h=K;var v=(()=>({}));var D=import.meta.dir,w=m.resolve(D,"../../public/uploaded");if(!v.existsSync(w))v.mkdirSync(w,{recursive:!0});var Te=(e={})=>{let r=e.dest?m.resolve(D,e.dest):w;return async(n)=>{try{let i=await n.body;n.req.files??={};for(let l of e?.fields??[]){let t=i[l];if(!t.name)continue;let f=`${l}_${h()}${m.extname(t?.name)}`,o=m.join(r,f);await Bun.write(o,await t.arrayBuffer()),n.req.files[l]=o}}catch(i){return console.error("File upload error:",i),n.json({status:500,message:"Error uploading files"},500)}}};export{Te as fileSaveMiddleware};
1
+ import x from"path";import{randomUUID as S}from"crypto";var a={randomUUID:S};import{randomFillSync as E}from"crypto";var l=new Uint8Array(256),u=l.length;function i(){if(u>l.length-16)E(l),u=0;return l.slice(u,u+=16)}var o=[];for(let r=0;r<256;++r)o.push((r+256).toString(16).slice(1));function w(r,n=0){return(o[r[n+0]]+o[r[n+1]]+o[r[n+2]]+o[r[n+3]]+"-"+o[r[n+4]]+o[r[n+5]]+"-"+o[r[n+6]]+o[r[n+7]]+"-"+o[r[n+8]]+o[r[n+9]]+"-"+o[r[n+10]]+o[r[n+11]]+o[r[n+12]]+o[r[n+13]]+o[r[n+14]]+o[r[n+15]]).toLowerCase()}function T(r,n,t){if(a.randomUUID&&!n&&!r)return a.randomUUID();r=r||{};let e=r.random??r.rng?.()??i();if(e.length<16)throw Error("Random bytes length must be >= 16");if(e[6]=e[6]&15|64,e[8]=e[8]&63|128,n){if(t=t||0,t<0||t+16>n.length)throw RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let m=0;m<16;++m)n[t+m]=e[m];return n}return w(e)}var v=T;import*as d from"fs";var I=import.meta.dir,y=x.resolve(I,"../../public/uploaded");if(!d.existsSync(y))d.mkdirSync(y,{recursive:!0});var lr=(r={})=>{let n=r.dest?x.resolve(I,r.dest):y;return async(t)=>{try{let e=await t.body;t.req.files??={};for(let m of r?.fields??[]){let g=e[m];if(!g.name)continue;let p=`${m}_${v()}${x.extname(g?.name)}`,U=x.join(n,p);await Bun.write(U,await g.arrayBuffer()),t.req.files[m]=U}}catch(e){return console.error("File upload error:",e),t.json({status:500,message:"Error uploading files"},500)}}};export{lr as fileSaveMiddleware};
@@ -1 +1 @@
1
- function G(q,E){if(!q)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(B)=>{try{let z=B.cookies?.accessToken??B.req?.headers?.get("Authorization");if(!z)return B.json({message:"Unauthorized",error:"No token provided"},401);if(z.startsWith("Bearer "))z=z.slice(7);let A=q?.verify(z,E);if(!A)return B.json({message:"Unauthorized",error:"Token could not be decoded"},401);B.set("user",A)}catch(z){let A="Invalid token";if(z.name==="TokenExpiredError")A="Token expired";else if(z.name==="JsonWebTokenError")A="Malformed or tampered token";return B.json({message:"Unauthorized",error:A},401)}}}function H(q,E,B){if(!q)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!E)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(z)=>{try{let A=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!A)return z.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=q?.verify(A,B);if(!C)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let F=await E.findById(C._id).select("-password -refreshToken");if(!F)return z.json({message:"Unauthorized: User not found"},404);z.set("user",F);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 z.json({message:"Unauthorized",error:C},401)}}}var L=(q)=>{if(!q.app)throw Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.jwt)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;let{routes:E,jwt:B,jwtSecret:z}=q,A=G(B,z);return(C)=>{if(!E?.length||E?.includes(C.url.pathname))return A(C)}},N=(q)=>{if(!q.app)throw Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.userModel)throw Error("User model is not defined, please provide userModel to authenticateJwt Function");if(!q.jwt)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;let{routes:E,jwt:B,jwtSecret:z,userModel:A}=q,C=H(B,A,z);return(F)=>{if(E?.length===0||E?.includes(F.url.pathname))return C(F)}};export{N as authenticateJwtDB,L as authenticateJwt};
1
+ function G(q,E){if(!q)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(B)=>{try{let z=B.cookies?.accessToken??B.req?.headers?.get("Authorization");if(!z)return B.json({message:"Unauthorized",error:"No token provided"},401);if(z.startsWith("Bearer "))z=z.slice(7);let A=q?.verify(z,E);if(!A)return B.json({message:"Unauthorized",error:"Token could not be decoded"},401);B.set("user",A)}catch(z){let A="Invalid token";if(z.name==="TokenExpiredError")A="Token expired";else if(z.name==="JsonWebTokenError")A="Malformed or tampered token";return B.json({message:"Unauthorized",error:A},401)}}}function H(q,E,B){if(!q)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!E)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(z)=>{try{let A=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!A)return z.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=q?.verify(A,B);if(!C)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let F=await E.findById(C._id).select("-password -refreshToken");if(!F)return z.json({message:"Unauthorized: User not found"},404);z.set("user",F);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 z.json({message:"Unauthorized",error:C},401)}}}var L=(q)=>{if(!q.app)throw Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.jwt)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;if(!q.jwtSecret)throw Error("jwtSecret is required for authenticateJwt");let{routes:E,jwt:B,jwtSecret:z}=q,A=G(B,z);return(C)=>{if(!E?.length||E?.includes(C.url.pathname))return A(C)}},N=(q)=>{if(!q.app)throw Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.userModel)throw Error("User model is not defined, please provide userModel to authenticateJwt Function");if(!q.jwt)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;if(!q.jwtSecret)throw Error("jwtSecret is required for authenticateJwtDB");let{routes:E,jwt:B,jwtSecret:z,userModel:A}=q,C=H(B,A,z);return(F)=>{if(E?.length===0||E?.includes(F.url.pathname))return C(F)}};export{N as authenticateJwtDB,L as authenticateJwt};
@@ -1,16 +1,16 @@
1
- function Q(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 $=Object.freeze({});class Y{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=$;urlObject=null;constructor(L,I,z,G,U,K){this.req=L,this.server=I,this.path=z,this.param=G,this.env=U,this.executionContext=K,this.headers=null}setHeader(L,I){if(!this.headers)this.headers=new Headers;return this.headers.set(L,I),this}removeHeader(L){if(this.headers)this.headers.delete(L);return this}set(L,I){if(this.contextData===$)this.contextData={};return this.contextData[L]=I,this}get(L){if(this.contextData===$)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):$;return this.parsedQuery}get params(){return this.param?this.param:$}get body(){if(this.req.method==="GET")return Promise.resolve($);if(!this.parsedBody)this.parsedBody=(async()=>{try{let L=await f(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,I=200,z){if(!this.headers){if(!z)return new Response(L,{status:I,headers:{"Content-Type":"text/plain; charset=utf-8"}});let G={"Content-Type":"text/plain; charset=utf-8"};return N(z,G),new Response(L,{status:I,headers:G})}if(z)w(this.headers,z);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response(L,{status:I,headers:this.headers})}send(L,I=200,z){let G,U;if(L instanceof Uint8Array||L instanceof ArrayBuffer)G="application/octet-stream",U=L;else if(L!==null&&typeof L==="object")G="application/json; charset=utf-8",U=JSON.stringify(L);else if(typeof L==="string")G="text/plain; charset=utf-8",U=L;else G="text/plain; charset=utf-8",U=String(L);if(!this.headers){if(!z)return new Response(U,{status:I,headers:{"Content-Type":G}});let K={"Content-Type":G};return N(z,K),new Response(U,{status:I,headers:K})}if(z)w(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",G);return new Response(U,{status:I,headers:this.headers})}json(L,I=200,z){if(!this.headers){if(!z)return Response.json(L,{status:I,headers:{"Content-Type":"application/json; charset=utf-8"}});let G={"Content-Type":"application/json; charset=utf-8"};return N(z,G),Response.json(L,{status:I,headers:G})}if(z)w(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:I,headers:this.headers})}file(L,I,z=200,G){let U=Bun.file(L);if(!this.headers){if(!G)return new Response(U,{status:z,headers:{"Content-Type":I??Q(L)}});let K={"Content-Type":I??Q(L)};return N(G,K),new Response(U,{status:z,headers:K})}if(G)w(this.headers,G);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",I??Q(L));return new Response(U,{status:z,headers:this.headers})}async ejs(L,I={},z=200){console.log("this method is diabled now for some time")}redirect(L,I=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",L),new Response(null,{status:I,headers:this.headers})}setCookie(L,I,z={}){if(!this.headers)this.headers=new Headers;let G=`${encodeURIComponent(L)}=${encodeURIComponent(I)}`;if(z.maxAge)G+=`; Max-Age=${z.maxAge}`;if(z.expires)G+=`; Expires=${z.expires.toUTCString()}`;if(z.path)G+=`; Path=${z.path}`;if(z.domain)G+=`; Domain=${z.domain}`;if(z.secure)G+="; Secure";if(z.httpOnly)G+="; HttpOnly";if(z.sameSite)G+=`; SameSite=${z.sameSite}`;return this.headers.append("Set-Cookie",G),this}get cookies(){if(!this.parsedCookies){let L=this.req.headers.get("cookie");this.parsedCookies=L?S(L):$}return this.parsedCookies}stream(L){let I=new Headers(this.headers??new Headers),z=new ReadableStream({async start(G){await L(G),G.close()}});return new Response(z,{headers:I})}yieldStream(L){return new Response}}function w(L,I){for(let z in I)L.set(z,I[z])}function N(L,I){for(let z in L)I[z]=L[z]}function S(L){return Object.fromEntries(L.split(";").map((I)=>{let[z,...G]=I.trim().split("=");return[z,decodeURIComponent(G.join("="))]}))}async function f(L){let I=L.headers.get("Content-Type")||"";if(!I)return{};if(L.headers.get("Content-Length")==="0"||!L.body)return{};if(I.startsWith("application/json"))return await L.json();if(I.startsWith("application/x-www-form-urlencoded")){let G=await L.text();return Object.fromEntries(new URLSearchParams(G))}if(I.startsWith("multipart/form-data")){let G=await L.formData(),U={};for(let[K,V]of G.entries())U[K]=V;return U}return{error:"Unknown request body type"}}var D=(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 F(L,I,z){if(!I?.length)return;for(let G=0;G<I.length;G++){let U=I[G](...z),K=U instanceof Promise?await U:U;if(K&&L!=="onRequest")return K}}async function B(L,I,z){for(let G of L){let U=await G(I,z);if(U)return U}}async function _(L,I,z){let G=await P(L,I,z),U=D(G)?await G:G;if(U)return U}async function P(L,I,z){if(I.endsWith("/"))I=I.slice(0,-1);if(!L.filters.has(I))if(L.filterFunction.length)for(let G of L.filterFunction){let U=await G(z);if(U)return U}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function M(L,I,z){if(L.staticPath){let X=!0;if(L.staticRequestPath)X=z.startsWith(L.staticRequestPath);if(X){let E=await b(L,z,I);if(E)return E}}let K=(L.router.find(I.req.method,"*")?.handler).slice(-1);if(K.length>0){let X=await K[0](I);if(j(X))return X}let V=await Promise.resolve(L.routeNotFoundFunc(I));return j(V)?V:A(404,`404 Route not found for ${z}`)}function A(L,I){return new Response(JSON.stringify({error:I}),{status:L,headers:{"Content-Type":"application/json"}})}async function b(L,I,z){if(!L.staticPath)return null;let G=`${L.staticPath}${I}`;if(await Bun.file(G).exists()){let K=Q(G);return z.file(G,K,200)}return null}var J=(L)=>L.constructor.name==="AsyncFunction",O=(L,I,z,...G)=>{if(I.length>5)L.push(`
1
+ function Z(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 T=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],W=Object.freeze({}),H="ALL";class w{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=W;urlObject=null;constructor(L,G,z,I,N,K){this.req=L,this.server=G,this.path=z,this.param=I,this.env=N,this.executionContext=K,this.headers=null}setHeader(L,G){if(!this.headers)this.headers=new Headers;return this.headers.set(L,G),this}removeHeader(L){if(this.headers)this.headers.delete(L);return this}set(L,G){if(this.contextData===W)this.contextData={};return this.contextData[L]=G,this}get(L){if(this.contextData===W)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):W;return this.parsedQuery}get params(){return this.param?this.param:W}get body(){if(this.req.method==="GET")return Promise.resolve(W);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,G=200,z){if(!this.headers){if(!z)return new Response(L,{status:G,headers:{"Content-Type":"text/plain; charset=utf-8"}});let I={"Content-Type":"text/plain; charset=utf-8"};return E(z,I),new Response(L,{status:G,headers:I})}if(z)V(this.headers,z);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response(L,{status:G,headers:this.headers})}send(L,G=200,z){let I,N;if(L instanceof Uint8Array||L instanceof ArrayBuffer)I="application/octet-stream",N=L;else if(L!==null&&typeof L==="object")I="application/json; charset=utf-8",N=JSON.stringify(L);else if(typeof L==="string")I="text/plain; charset=utf-8",N=L;else I="text/plain; charset=utf-8",N=String(L);if(!this.headers){if(!z)return new Response(N,{status:G,headers:{"Content-Type":I}});let K={"Content-Type":I};return E(z,K),new Response(N,{status:G,headers:K})}if(z)V(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",I);return new Response(N,{status:G,headers:this.headers})}json(L,G=200,z){if(!this.headers){if(!z)return Response.json(L,{status:G,headers:{"Content-Type":"application/json; charset=utf-8"}});let I={"Content-Type":"application/json; charset=utf-8"};return E(z,I),Response.json(L,{status:G,headers:I})}if(z)V(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:G,headers:this.headers})}file(L,G,z=200,I){let N=Bun.file(L);if(!this.headers){if(!I)return new Response(N,{status:z,headers:{"Content-Type":G??Z(L)}});let K={"Content-Type":G??Z(L)};return E(I,K),new Response(N,{status:z,headers:K})}if(I)V(this.headers,I);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",G??Z(L));return new Response(N,{status:z,headers:this.headers})}async ejs(L,G={},z=200){console.log("this method is diabled now for some time")}redirect(L,G=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",L),new Response(null,{status:G,headers:this.headers})}setCookie(L,G,z={}){if(!this.headers)this.headers=new Headers;let I=`${encodeURIComponent(L)}=${encodeURIComponent(G)}`;if(z.maxAge)I+=`; Max-Age=${z.maxAge}`;if(z.expires)I+=`; Expires=${z.expires.toUTCString()}`;if(z.path)I+=`; Path=${z.path}`;if(z.domain)I+=`; Domain=${z.domain}`;if(z.secure)I+="; Secure";if(z.httpOnly)I+="; HttpOnly";if(z.sameSite)I+=`; SameSite=${z.sameSite}`;return this.headers.append("Set-Cookie",I),this}get cookies(){if(!this.parsedCookies){let L=this.req.headers.get("cookie");this.parsedCookies=L?M(L):W}return this.parsedCookies}stream(L){let G=new Headers(this.headers??new Headers),z=new ReadableStream({async start(I){await L(I),I.close()}});return new Response(z,{headers:G})}yieldStream(L){return new Response}}function V(L,G){for(let z in G)L.set(z,G[z])}function E(L,G){for(let z in L)G[z]=L[z]}function M(L){return Object.fromEntries(L.split(";").map((G)=>{let[z,...I]=G.trim().split("=");return[z,decodeURIComponent(I.join("="))]}))}async function P(L){let G=L.headers.get("Content-Type")||"";if(!G)return{};if(!L.body)return{};if(G.startsWith("application/json"))try{return await L.json()}catch(z){throw Error("Invalid request body format")}if(G.startsWith("application/x-www-form-urlencoded")){let z=await L.text();return Object.fromEntries(new URLSearchParams(z))}if(G.startsWith("multipart/form-data")){let z=await L.formData(),I={};for(let[N,K]of z.entries())I[N]=K;return I}return{error:"Unknown request body type"}}var j=(L)=>L!==null&&typeof L==="object"&&typeof L.then==="function",A=(L)=>L!==null&&typeof L==="object"&&typeof L.status==="number"&&typeof L.headers==="object";async function C(L,G,z){if(!G?.length)return;for(let I=0;I<G.length;I++){let N=G[I](...z),K=N instanceof Promise?await N:N;if(K&&L!=="onRequest")return K}}async function n(L,G,z){return null}async function F(L,G,z){for(let I of L){let N=await I(G,z);if(N)return N}}async function B(L,G,z){let I=await v(L,G,z),N=j(I)?await I:I;if(N)return N}async function v(L,G,z){if(G.endsWith("/"))G=G.slice(0,-1);if(!L.filters.has(G))if(L.filterFunction.length)for(let I of L.filterFunction){let N=await I(z);if(N)return N}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function l(L,G,z,I){if(!L.filters.has(G))if(L.filterFunction.length)for(let N of L.filterFunction){let K=await N(z,I);if(K)return K}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function S(L,G,z){if(L.staticPath){let Q=!0;if(L.staticRequestPath)Q=z.startsWith(L.staticRequestPath);if(Q){let X=await f(L,z,G);if(X)return X}}let N=L.router.find(G.req.method,"*")?.handler;if(N?.length>0){let Q=await N[N.length-1](G);if(A(Q))return Q}let K=await Promise.resolve(L.routeNotFoundFunc(G));return A(K)?K:D(404,`404 Route not found for ${z}`)}function D(L,G){return new Response(JSON.stringify({error:G}),{status:L,headers:{"Content-Type":"application/json"}})}async function f(L,G,z){if(!L.staticPath)return null;let I=`${L.staticPath}${G}`;if(await Bun.file(I).exists()){let K=Z(I);return z.file(I,K,200)}return null}var Y=(L)=>L.constructor.name==="AsyncFunction",_=(L,G,z,...I)=>{if(G.length>5)L.push(`
2
2
  for (let i = 0; i < diesel.hooks.${z}.length; i++) {
3
- const result = diesel.hooks.${z}[i](${G});
3
+ const result = diesel.hooks.${z}[i](${I});
4
4
  const finalResult = result instanceof Promise ? await result : result;
5
5
  if (finalResult && '${z}' !== 'onRequest') return finalResult
6
6
  }
7
- `);else I?.forEach((U,K)=>{if(J(U))L.push(`
8
- const ${z}${K}Result = await diesel.hooks.${z}[${K}](${G})
7
+ `);else G?.forEach((N,K)=>{if(Y(N))L.push(`
8
+ const ${z}${K}Result = await diesel.hooks.${z}[${K}](${I})
9
9
  if (${z}${K}Result && '${z}' !== 'onRequest') return ${z}${K}Result
10
10
  `);else L.push(`
11
- const ${z}${K}Result = diesel.hooks.${z}[${K}](${G})
11
+ const ${z}${K}Result = diesel.hooks.${z}[${K}](${I})
12
12
  if (${z}${K}Result && '${z}' !== 'onRequest') return ${z}${K}Result
13
- `)})},q=(L)=>{L.push(`
13
+ `)})},b=(L)=>{L.push(`
14
14
  let pathname;
15
15
  const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
16
16
  let i = start;
@@ -28,9 +28,9 @@ function Q(L){switch(L.split(".").pop()?.toLowerCase()){case"js":return"applicat
28
28
  if (!pathname) {
29
29
  pathname = req.url.slice(start, i);
30
30
  }
31
- `)};var n=(L)=>{let I=[],z=L?.hasPreHandlerHook?L.hooks.preHandler:[],G=L?.hasOnSendHook?L.hooks.onSend:[];if(q(I),I.push(`
31
+ `)};var i=(L)=>{let G=[],z=L?.hasPreHandlerHook?L.hooks.preHandler:[],I=L?.hasOnSendHook?L.hooks.onSend:[];if(b(G),G.push(`
32
32
  const matchedRouteHandler = diesel.router.find(req.method, pathname);
33
- `),I.push(`
33
+ `),G.push(`
34
34
  const ctx = new Context(
35
35
  req,
36
36
  server,
@@ -39,10 +39,10 @@ function Q(L){switch(L.split(".").pop()?.toLowerCase()){case"js":return"applicat
39
39
  env,
40
40
  executionContext
41
41
  )
42
- `),L.hasFilterEnabled)I.push(`
42
+ `),L.hasFilterEnabled)G.push(`
43
43
  const filterResponse = await runFilter(diesel, pathname, ctx);
44
44
  if (filterResponse) return filterResponse;
45
- `);if(L.hasPreHandlerHook)O(I,z,"preHandler","ctx");if(I.push(`
45
+ `);if(L.hasPreHandlerHook)_(G,z,"preHandler","ctx");if(G.push(`
46
46
  let finalResult
47
47
  const handlers = matchedRouteHandler?.handler;
48
48
 
@@ -57,53 +57,53 @@ function Q(L){switch(L.split(".").pop()?.toLowerCase()){case"js":return"applicat
57
57
  if (finalResult) break;
58
58
  }
59
59
  }
60
- `),L.hasOnSendHook)O(I,G,"onSend","ctx","finalResult");I.push(`
60
+ `),L.hasOnSendHook)_(G,I,"onSend","ctx","finalResult");G.push(`
61
61
  if (finalResult) return finalResult;
62
- `),I.push(`
62
+ `),G.push(`
63
63
  return await handleRouteNotFound(diesel, ctx, pathname);
64
- `);let U=`
64
+ `);let N=`
65
65
  return async function pipeline(req, diesel, server, env, executionContext) {
66
- ${I.join(`
66
+ ${G.join(`
67
67
  `)}
68
68
  }
69
- `;return Function("runFilter","handleRouteNotFound","generateErrorResponse","Context","isPromise",U)(_,M,A,Y,D)},r=(L,I,z,...G)=>{let U=[],K;if(typeof G[0]==="string"||typeof G[0]==="object")K=G[0];let V=G,X=L?.hasOnReqHook?L.hooks.onRequest:[],E=L.filters.has(z),C=L.filterFunction;if(X&&X?.length>0)U.push(`
69
+ `;return Function("runFilter","handleRouteNotFound","generateErrorResponse","Context","isPromise",N)(B,S,D,w,j)},t=(L,G,z,...I)=>{let N=[],K;if(typeof I[0]==="string"||typeof I[0]==="object")K=I[0];let Q=I,X=L?.hasOnReqHook?L.hooks.onRequest:[],g=L.filters.has(z),J=L.filterFunction;if(X&&X?.length>0)N.push(`
70
70
  const onRequestResult = await runHooks(
71
71
  "onRequest",
72
72
  onRequestHooks,
73
73
  [req, "${z}", server]
74
74
  );
75
75
  if (onRequestResult) return onRequestResult;
76
- `);if(L.hasFilterEnabled){if(!E)U.push(`if (${C.length}) {
76
+ `);if(L.hasFilterEnabled){if(!g)N.push(`if (${J.length}) {
77
77
  for (const filterFunction of filterFunctions) {
78
78
  const filterResult = await filterFunction(req, server);
79
79
  if (filterResult) return filterResult;
80
80
  }
81
81
  } else {
82
82
  return Response.json({ error: "Protected route, authentication required" }, { status: 401 });
83
- }`)}if(U.push(`
84
- if ("${I}" !== req.method)
83
+ }`)}if(N.push(`
84
+ if ("${G}" !== req.method)
85
85
  return new Response("Method Not Allowed", { status: 405 });
86
- `),typeof K<"u")if(typeof K==="string")U.push(`
86
+ `),typeof K<"u")if(typeof K==="string")N.push(`
87
87
  return new Response(${JSON.stringify(K)});
88
- `);else{let W=JSON.stringify(K);U.push(`
89
- return new Response(${JSON.stringify(W)}, {
88
+ `);else{let $=JSON.stringify(K);N.push(`
89
+ return new Response(${JSON.stringify($)}, {
90
90
  headers: { "content-type": "application/json; charset=utf-8" }
91
91
  });
92
- `)}else if(V.length===1){let W=V[0];if(J(W))U.push(`
92
+ `)}else if(Q.length===1){let $=Q[0];if(Y($))N.push(`
93
93
  const response = await handlers[0](req, server);
94
94
  if (response instanceof Response) return response;
95
- `);else U.push(`
95
+ `);else N.push(`
96
96
  const response = handlers[0](req, server);
97
97
  if (response instanceof Response) return response;
98
- `)}else V.forEach((W,Z)=>{if(J(W))U.push(`
99
- const response${Z} = await handlers[${Z}](req, server);
100
- if (response${Z} instanceof Response) return response${Z};
101
- `);else U.push(`
102
- const response${Z} = handlers[${Z}](req, server);
103
- if (response${Z} instanceof Response) return response${Z};
104
- `)});let v=`
98
+ `)}else Q.forEach(($,U)=>{if(Y($))N.push(`
99
+ const response${U} = await handlers[${U}](req, server);
100
+ if (response${U} instanceof Response) return response${U};
101
+ `);else N.push(`
102
+ const response${U} = handlers[${U}](req, server);
103
+ if (response${U} instanceof Response) return response${U};
104
+ `)});let O=`
105
105
  return async function(req, server) {
106
- ${U.join(`
106
+ ${N.join(`
107
107
  `)}
108
108
  }
109
- `;return Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",v)(B,V,F,C,X)};export{n as buildRequestPipeline,r as BunRequestPipline};
109
+ `;return Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",O)(F,Q,C,J,X)};export{i as buildRequestPipeline,t as BunRequestPipline};
@@ -1,11 +1,12 @@
1
1
  export interface Router {
2
- add(method: string, path: string, handler: Function): void;
2
+ add(method: string, path: string, handler: Function | Function[]): void;
3
3
  find(method: string, path: string): Find;
4
4
  addMiddleware(path: string, handlers: Function | Function[]): void;
5
5
  }
6
6
  export interface Find {
7
7
  params: Record<string, string> | undefined;
8
- handler: Function[];
8
+ middlewares: Function[] | undefined;
9
+ handler: Array<Function> | undefined;
9
10
  }
10
11
  export declare class RouterFactory {
11
12
  static create(name?: string): Router;
@@ -1 +1 @@
1
- var v=Object.freeze({});class L{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class D{root;globalMiddlewares;constructor(){this.root=new L,this.globalMiddlewares=[]}pushMiddleware(F,u){if(!Array.isArray(u))u=[u];if(F==="/"){this.globalMiddlewares.push(...u);return}let i=this.root,f=F.split("/").filter(Boolean);for(let x of f){let R=x;if(x.startsWith(":"))R=":";else if(x.startsWith("*"))i.middlewares.push(...u);if(!i.children[R])i.children[R]=new L;i=i.children[R]}i.middlewares.push(...u)}addMiddleware(F,u){return this.pushMiddleware(F,u)}insert(F,u,i){let f=this.root;if(u==="/"){f.handlers[F]=i,f.params=v;return}let x=u.split("/").filter(Boolean),R={};for(let A=0;A<x.length;A++){let E=x[A],w=E,g="";if(E.startsWith(":"))w=":",g=E.slice(1);if(!f.children[w])f.children[w]=new L;if(f=f.children[w],g)R[g]=A,f.paramName=g}f.params=R,f.handlers[F]=i}add(F,u,i){return this.insert(F,u,i)}search(F,u){let i=this.root,f=u.split("/"),x=this.globalMiddlewares.slice(),R;for(let A=0;A<f.length;A++){let E=f[A];if(E.length===0)continue;if(i.children[E])i=i.children[E];else if(i.children[":"]){if(i=i.children[":"],!R)R={};R[i.paramName]=E}else if(i.children["*"]){i=i.children["*"];break}else return{params:R,handler:x};if(i.middlewares.length>0){let w=i.middlewares;for(let g=0;g<w.length;g++)x.push(w[g])}}if(i.handlers[F])x.push(i.handlers[F]);if(i.handlers.ALL)x.push(i.handlers.ALL);return{params:R,handler:x}}find(F,u){return this.search(F,u)}}class H{static create(F){switch(F){case"t2":return new D;case"trie":return new D;default:return new D}}}export{H as RouterFactory};
1
+ var H=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],z=Object.freeze({}),P="ALL";class I{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class v{root;globalMiddlewares;constructor(){this.root=new I,this.globalMiddlewares=[]}pushMiddleware(F,f){if(!Array.isArray(f))f=[f];if(F==="/"){this.globalMiddlewares.push(...f);return}let u=this.root,g=F.split("/").filter(Boolean);for(let i of g){let x=i;if(i.startsWith(":"))x=":";else if(i.startsWith("*"))u.middlewares.push(...f);if(!u.children[x])u.children[x]=new I;u=u.children[x]}u.middlewares.push(...f)}addMiddleware(F,f){return this.pushMiddleware(F,f)}insert(F,f,u){let g=Array.isArray(u)?u:[u],i=this.root;if(f==="/"){if(i.handlers[F])return;i.handlers[F]=g,i.params=z;return}let x=f.split("/").filter(Boolean),E={};for(let R=0;R<x.length;R++){let L=x[R],A=L,D="";if(L.startsWith(":"))A=":",D=L.slice(1);if(!i.children[A])i.children[A]=new I;if(i=i.children[A],D)E[D]=R,i.paramName=D}if(i.params=E,i.handlers[F])return;i.handlers[F]=g}add(F,f,u){return this.insert(F,f,u)}search(F,f){let u=this.root,g=f.split("/"),i=this.globalMiddlewares.slice(),x;for(let E=0;E<g.length;E++){let R=g[E];if(R.length===0)continue;if(u.children[R])u=u.children[R];else if(u.children[":"]){if(u=u.children[":"],!x)x={};x[u.paramName]=R}else if(u.children["*"]){u=u.children["*"];break}else return{params:x,middlewares:i,handler:void 0};if(u.middlewares.length>0){let L=u.middlewares;for(let A=0;A<L.length;A++)i.push(L[A])}}if(u.handlers[F])return{params:x,middlewares:i,handler:u.handlers[F]};if(u.handlers[P])return{params:x,middlewares:i,handler:u.handlers[P]};return{params:x,middlewares:i,handler:void 0}}find(F,f){return this.search(F,f)}}class C{static create(F){switch(F){case"t2":return new v;case"trie":return new v;default:return new v}}}export{C as RouterFactory};
@@ -0,0 +1 @@
1
+ class C{children;isEndOfWord;handler;isDynamic;pattern;path;methodMap;segmentCount;params;middlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=null,this.isDynamic=!1,this.pattern="",this.path="",this.methodMap=new Map,this.segmentCount=0,this.params=[],this.middlewares=[]}}class F{root;cachedSegments;globalMiddlewares;constructor(){this.root=new C,this.cachedSegments=new Map,this.globalMiddlewares=[]}pushMidl(v,...j){let b=this.root,A=v.split("/").filter(Boolean);if(v==="/"){b.handler=j[0],this.globalMiddlewares.push(...j);return}for(let q of A){let z=q;if(q.startsWith(":"))z=":";else if(q.startsWith("*"))b.middlewares.push(...j);if(!b.children[z])b.children[z]=new C;b=b.children[z]}b.middlewares.push(...j),b.handler=j[0]}insert(v,j){let b=this.root,A=v.split("/").filter(Boolean);if(this.cachedSegments.set(v,A),v==="/"){b.isEndOfWord=!0,b.handler=j.handler,b.path=v,b.methodMap.set(j.method,j.handler),b.segmentCount=0,b.params=[];return}for(let q of A){let z=q,B=!1;if(q.startsWith(":"))B=!0,z=":";if(q==="*")z="*";if(!b.children[z])b.children[z]=new C;b=b.children[z],b.isDynamic=B,b.pattern=q}b.params=A.filter((q)=>q.startsWith(":")).map((q)=>q.slice(1)),b.isEndOfWord=!0,b.path=v,b.segmentCount=A.length,b.methodMap.set(j.method,j.handler),b.handler=j.handler}search(v,j){let b=this.root,A=this.cachedSegments.get(v)||v.split("/").filter(Boolean),q=[...this.globalMiddlewares];for(let B of A){let E=B;if(b.children[E])b=b.children[E];else if(b.children[":"])b=b.children[":"];else if(b.children["*"]){b=b.children["*"];break}else return{handler:q,params:{}};if(b.middlewares.length>0)q.push(...b.middlewares)}if(!b.isEndOfWord||b.segmentCount!==A.length)return{handler:q};let z=b.methodMap.get(j);if(z)q.push(z);return{params:b.params,handler:q}}}class G{trie=new F;add(v,j,b){this.trie.insert(j,{method:v,handler:b})}addMiddleware(v,...j){this.trie.pushMidl(v,...j)}find(v,j){return this.trie.search(j,v)}}export{G as OldTrieRouter};
File without changes
@@ -1,6 +1,7 @@
1
+ import { Find } from "./interface";
1
2
  declare class TrieNodes {
2
3
  children: Record<string, TrieNodes>;
3
- handlers: Record<string, Function>;
4
+ handlers: Record<string, Array<Function>>;
4
5
  middlewares: Function[];
5
6
  params: Record<string, number>;
6
7
  paramName: string;
@@ -12,15 +13,9 @@ export declare class TrieRouter {
12
13
  constructor();
13
14
  pushMiddleware(path: string, handlers: Function | Function[]): void;
14
15
  addMiddleware(path: string, handlers: Function | Function[]): void;
15
- insert(method: string, path: string, handler: Function): void;
16
- add(method: string, path: string, handler: Function): void;
17
- search(method: string, path: string): {
18
- params: Record<string, string> | undefined;
19
- handler: Function[];
20
- };
21
- find(method: string, path: string): {
22
- params: Record<string, string> | undefined;
23
- handler: Function[];
24
- };
16
+ insert(method: string, path: string, handler: Function | Function[]): void;
17
+ add(method: string, path: string, handler: Function | Function[]): void;
18
+ search(method: string, path: string): Find;
19
+ find(method: string, path: string): Find;
25
20
  }
26
21
  export {};
@@ -1 +1 @@
1
- var F=Object.freeze({});class C{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class M{root;globalMiddlewares;constructor(){this.root=new C,this.globalMiddlewares=[]}pushMiddleware(D,E){if(!Array.isArray(E))E=[E];if(D==="/"){this.globalMiddlewares.push(...E);return}let A=this.root,L=D.split("/").filter(Boolean);for(let H of L){let x=H;if(H.startsWith(":"))x=":";else if(H.startsWith("*"))A.middlewares.push(...E);if(!A.children[x])A.children[x]=new C;A=A.children[x]}A.middlewares.push(...E)}addMiddleware(D,E){return this.pushMiddleware(D,E)}insert(D,E,A){let L=this.root;if(E==="/"){L.handlers[D]=A,L.params=F;return}let H=E.split("/").filter(Boolean),x={};for(let I=0;I<H.length;I++){let P=H[I],z=P,f="";if(P.startsWith(":"))z=":",f=P.slice(1);if(!L.children[z])L.children[z]=new C;if(L=L.children[z],f)x[f]=I,L.paramName=f}L.params=x,L.handlers[D]=A}add(D,E,A){return this.insert(D,E,A)}search(D,E){let A=this.root,L=E.split("/"),H=this.globalMiddlewares.slice(),x;for(let I=0;I<L.length;I++){let P=L[I];if(P.length===0)continue;if(A.children[P])A=A.children[P];else if(A.children[":"]){if(A=A.children[":"],!x)x={};x[A.paramName]=P}else if(A.children["*"]){A=A.children["*"];break}else return{params:x,handler:H};if(A.middlewares.length>0){let z=A.middlewares;for(let f=0;f<z.length;f++)H.push(z[f])}}if(A.handlers[D])H.push(A.handlers[D]);if(A.handlers.ALL)H.push(A.handlers.ALL);return{params:x,handler:H}}find(D,E){return this.search(D,E)}}export{M as TrieRouter};
1
+ var q=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"],Y=Object.freeze({}),U="ALL";class R{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class f{root;globalMiddlewares;constructor(){this.root=new R,this.globalMiddlewares=[]}pushMiddleware(L,E){if(!Array.isArray(E))E=[E];if(L==="/"){this.globalMiddlewares.push(...E);return}let A=this.root,z=L.split("/").filter(Boolean);for(let x of z){let D=x;if(x.startsWith(":"))D=":";else if(x.startsWith("*"))A.middlewares.push(...E);if(!A.children[D])A.children[D]=new R;A=A.children[D]}A.middlewares.push(...E)}addMiddleware(L,E){return this.pushMiddleware(L,E)}insert(L,E,A){let z=Array.isArray(A)?A:[A],x=this.root;if(E==="/"){if(x.handlers[L])return;x.handlers[L]=z,x.params=Y;return}let D=E.split("/").filter(Boolean),C={};for(let I=0;I<D.length;I++){let F=D[I],P=F,H="";if(F.startsWith(":"))P=":",H=F.slice(1);if(!x.children[P])x.children[P]=new R;if(x=x.children[P],H)C[H]=I,x.paramName=H}if(x.params=C,x.handlers[L])return;x.handlers[L]=z}add(L,E,A){return this.insert(L,E,A)}search(L,E){let A=this.root,z=E.split("/"),x=this.globalMiddlewares.slice(),D;for(let C=0;C<z.length;C++){let I=z[C];if(I.length===0)continue;if(A.children[I])A=A.children[I];else if(A.children[":"]){if(A=A.children[":"],!D)D={};D[A.paramName]=I}else if(A.children["*"]){A=A.children["*"];break}else return{params:D,middlewares:x,handler:void 0};if(A.middlewares.length>0){let F=A.middlewares;for(let P=0;P<F.length;P++)x.push(F[P])}}if(A.handlers[L])return{params:D,middlewares:x,handler:A.handlers[L]};if(A.handlers[U])return{params:D,middlewares:x,handler:A.handlers[U]};return{params:D,middlewares:x,handler:void 0}}find(L,E){return this.search(L,E)}}export{f as TrieRouter};
package/dist/types.js ADDED
File without changes
@@ -1 +1 @@
1
- function b(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"}}var z=(g)=>g!==null&&typeof g==="object"&&typeof g.then==="function",f=(g)=>g!==null&&typeof g==="object"&&typeof g.status==="number"&&typeof g.headers==="object";async function M(g,n,j){if(!n?.length)return;for(let o=0;o<n.length;o++){let c=n[o](...j),w=c instanceof Promise?await c:c;if(w&&g!=="onRequest")return w}}async function N(g,n,j){return null}async function O(g,n,j){for(let o of g){let c=await o(n,j);if(c)return c}}async function Q(g,n,j){let o=await B(g,n,j),c=z(o)?await o:o;if(c)return c}async function B(g,n,j){if(n.endsWith("/"))n=n.slice(0,-1);if(!g.filters.has(n))if(g.filterFunction.length)for(let o of g.filterFunction){let c=await o(j);if(c)return c}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function U(g,n,j,o){if(!g.filters.has(n))if(g.filterFunction.length)for(let c of g.filterFunction){let w=await c(j,o);if(w)return w}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function V(g,n,j){if(g.staticPath){let y=!0;if(g.staticRequestPath)y=j.startsWith(g.staticRequestPath);if(y){let L=await G(g,j,n);if(L)return L}}let w=(g.router.find(n.req.method,"*")?.handler).slice(-1);if(w.length>0){let y=await w[0](n);if(f(y))return y}let C=await Promise.resolve(g.routeNotFoundFunc(n));return f(C)?C:D(404,`404 Route not found for ${j}`)}function D(g,n){return new Response(JSON.stringify({error:n}),{status:g,headers:{"Content-Type":"application/json"}})}async function G(g,n,j){if(!g.staticPath)return null;let o=`${g.staticPath}${n}`;if(await Bun.file(o).exists()){let w=b(o);return j.file(o,w,200)}return null}export{N as runMiddlewares,M as runHooks,Q as runFilter,G as handleStaticFiles,V as handleRouteNotFound,B as handleFilterRequest,U as handleBunFilterRequest,D as generateErrorResponse,O as executeBunMiddlewares};
1
+ function L(n){switch(n.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 b=(n)=>n!==null&&typeof n==="object"&&typeof n.then==="function",f=(n)=>n!==null&&typeof n==="object"&&typeof n.status==="number"&&typeof n.headers==="object";async function K(n,g,c){if(!g?.length)return;for(let j=0;j<g.length;j++){let o=g[j](...c),w=o instanceof Promise?await o:o;if(w&&n!=="onRequest")return w}}async function M(n,g,c){return null}async function N(n,g,c){for(let j of n){let o=await j(g,c);if(o)return o}}async function O(n,g,c){let j=await z(n,g,c),o=b(j)?await j:j;if(o)return o}async function z(n,g,c){if(g.endsWith("/"))g=g.slice(0,-1);if(!n.filters.has(g))if(n.filterFunction.length)for(let j of n.filterFunction){let o=await j(c);if(o)return o}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function Q(n,g,c,j){if(!n.filters.has(g))if(n.filterFunction.length)for(let o of n.filterFunction){let w=await o(c,j);if(w)return w}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function U(n,g,c){if(n.staticPath){let y=!0;if(n.staticRequestPath)y=c.startsWith(n.staticRequestPath);if(y){let C=await D(n,c,g);if(C)return C}}let o=n.router.find(g.req.method,"*")?.handler;if(o?.length>0){let y=await o[o.length-1](g);if(f(y))return y}let w=await Promise.resolve(n.routeNotFoundFunc(g));return f(w)?w:B(404,`404 Route not found for ${c}`)}function B(n,g){return new Response(JSON.stringify({error:g}),{status:n,headers:{"Content-Type":"application/json"}})}async function D(n,g,c){if(!n.staticPath)return null;let j=`${n.staticPath}${g}`;if(await Bun.file(j).exists()){let w=L(j);return c.file(j,w,200)}return null}export{M as runMiddlewares,K as runHooks,O as runFilter,D as handleStaticFiles,U as handleRouteNotFound,z as handleFilterRequest,Q as handleBunFilterRequest,B as generateErrorResponse,N as executeBunMiddlewares};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
File without changes