diesel-core 1.1.7 → 1.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ctx.js CHANGED
@@ -1 +1 @@
1
- var J=Object.create;var{getPrototypeOf:H,defineProperty:N,getOwnPropertyNames:M}=Object;var Q=Object.prototype.hasOwnProperty;var b=(E,L,G)=>{G=E!=null?J(H(E)):{};let A=L||!E||!E.__esModule?N(G,"default",{value:E,enumerable:!0}):G;for(let F of M(E))if(!Q.call(A,F))N(A,F,{get:()=>E[F],enumerable:!0});return A};var B=((E)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(E,{get:(L,G)=>(typeof require!=="undefined"?require:L)[G]}):E)(function(E){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+E+'" is not supported')});function R(E){switch(E.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function v(E,L){if(!E)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(G)=>{try{let A=G.cookies?.accessToken||G.req?.headers?.get("Authorization");if(!A)return G.json({message:"Unauthorized: No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let F=E?.verify(A,L);if(!F)return G.json({message:"Unauthorized: Invalid token"},401);G.set("user",F);return}catch(A){return G.json({message:"Unauthorized: Invalid token",error:A?.message},401)}}}function T(E,L,G){if(!E)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!L)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(A)=>{try{let F=A.cookies?.accessToken||A.req?.headers?.get("Authorization");if(!F)return A.json({message:"Unauthorized: No token provided"},401);if(F.startsWith("Bearer "))F=F.slice(7);let Z=E?.verify(F,G);if(!Z)return A.json({message:"Unauthorized: Invalid token"},401);let Y=await L.findById(Z._id).select("-password -refreshToken");if(!Y)return A.json({message:"Unauthorized: User not found"},401);A.set("user",Y);return}catch(F){return A.json({message:"Unauthorized: Authentication failed",error:F?.message},401)}}}function C(E,L,G){let A=null,F=null,Z=null,Y=null,I={};return{req:E,server:L,url:G,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(z,K){return this.headers.set(z,K),this},removeHeader(z){return this.headers.delete(z),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!A)try{A=Object.fromEntries(this.url.searchParams)}catch(z){throw new Error("Failed to parse query parameters")}return A},get params(){if(!F&&this.req.routePattern)try{F=D(this.req.routePattern,this.url.pathname)}catch(z){throw new Error("Failed to extract route parameters")}return F??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!Y)Y=(async()=>{let z=await f(this.req);if(z.error)throw new Error(z.error);return Object.keys(z).length===0?null:z})();return Y},set(z,K){return I[z]=K,this},get(z){return I[z]},text(z,K){if(K)this.status=K;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(z,{status:this.status,headers:this.headers})},send(z,K){if(K)this.status=K;let O=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),X=z instanceof Uint8Array?"Uint8Array":z instanceof ArrayBuffer?"ArrayBuffer":typeof z;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",O.get(X)??"text/plain; charset=utf-8");let $=X==="object"&&z!==null?JSON.stringify(z):z;return new Response($,{status:this.status,headers:this.headers})},json(z,K){if(K)this.status=K;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(z),{status:this.status,headers:this.headers})},file(z,K,O){if(O)this.status=O;let X=Bun.file(z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",K??R(z));return new Response(X,{status:this.status,headers:this.headers})},async ejs(z,K={},O){if(O)this.status=O;let X;try{X=await import("ejs"),X=X.default||X}catch($){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let $=await Bun.file(z).text(),V=X.render($,K),W=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(V,{status:this.status,headers:W})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}},redirect(z,K){if(K)this.status=K;else this.status=302;return this.headers.set("Location",z),new Response(null,{status:this.status,headers:this.headers})},setCookie(z,K,O={}){let X=`${encodeURIComponent(z)}=${encodeURIComponent(K)}`;if(O.maxAge)X+=`; Max-Age=${O.maxAge}`;if(O.expires)X+=`; Expires=${O.expires.toUTCString()}`;if(O.path)X+=`; Path=${O.path}`;if(O.domain)X+=`; Domain=${O.domain}`;if(O.secure)X+="; Secure";if(O.httpOnly)X+="; HttpOnly";if(O.sameSite)X+=`; SameSite=${O.sameSite}`;return this.headers.append("Set-Cookie",X),this},get cookies(){if(!Z){let z=this.req.headers.get("cookie");Z=z?U(z):{}}return Z}}}function U(E){return Object.fromEntries(E.split(";").map((L)=>{let[G,...A]=L.trim().split("=");return[G,decodeURIComponent(A.join("="))]}))}function D(E,L){let G={},A=E.split("/"),[F]=L.split("?"),Z=F.split("/");if(A.length!==Z.length)return null;for(let Y=0;Y<A.length;Y++)if(A[Y].startsWith(":"))G[A[Y].slice(1)]=Z[Y];return G}async function f(E){let L=E.headers.get("Content-Type");if(!L)return{};if(E.headers.get("Content-Length")==="0"||!E.body)return{};try{if(L.startsWith("application/json"))return await E.json();if(L.startsWith("application/x-www-form-urlencoded")){let A=await E.text();return Object.fromEntries(new URLSearchParams(A))}if(L.startsWith("multipart/form-data")){let A=await E.formData(),F={};for(let[Z,Y]of A.entries())F[Z]=Y;return F}return{error:"Unknown request body type"}}catch(A){return{error:"Invalid request body format"}}}export{C as default};
1
+ var J=Object.create;var{getPrototypeOf:H,defineProperty:N,getOwnPropertyNames:M}=Object;var Q=Object.prototype.hasOwnProperty;var B=(E,X,K)=>{K=E!=null?J(H(E)):{};let A=X||!E||!E.__esModule?N(K,"default",{value:E,enumerable:!0}):K;for(let F of M(E))if(!Q.call(A,F))N(A,F,{get:()=>E[F],enumerable:!0});return A};var C=((E)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(E,{get:(X,K)=>(typeof require!=="undefined"?require:X)[K]}):E)(function(E){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+E+'" is not supported')});function R(E){switch(E.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function v(E,X){if(!E)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(K)=>{try{let A=K.cookies?.accessToken||K.req?.headers?.get("Authorization");if(!A)return K.json({message:"Unauthorized: No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let F=E?.verify(A,X);if(!F)return K.json({message:"Unauthorized: Invalid token"},401);K.set("user",F)}catch(A){return console.error("JWT verification error:",A),K.json({message:"Unauthorized: Invalid token",error:A?.message},401)}}}function T(E,X,K){if(!E)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!X)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(A)=>{try{let F=A.cookies?.accessToken||A.req?.headers?.get("Authorization");if(!F)return A.json({message:"Unauthorized: No token provided"},401);if(F.startsWith("Bearer "))F=F.slice(7);let Z=E?.verify(F,K);if(!Z)return A.json({message:"Unauthorized: Invalid token"},401);let Y=await X.findById(Z._id).select("-password -refreshToken");if(!Y)return A.json({message:"Unauthorized: User not found"},401);A.set("user",Y);return}catch(F){return A.json({message:"Unauthorized: Authentication failed",error:F?.message},401)}}}function U(E,X,K){let A=null,F=null,Z=null,Y=null,I={};return{req:E,server:X,url:K,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(z,G){return this.headers.set(z,G),this},removeHeader(z){return this.headers.delete(z),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!A)try{A=Object.fromEntries(this.url.searchParams)}catch(z){throw new Error("Failed to parse query parameters")}return A},get params(){if(!F&&this.req.routePattern)try{F=f(this.req.routePattern,this.url.pathname)}catch(z){throw new Error("Failed to extract route parameters")}return F??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!Y)Y=(async()=>{let z=await b(this.req);if(z.error)throw new Error(z.error);return Object.keys(z).length===0?null:z})();return Y},set(z,G){return I[z]=G,this},get(z){return I[z]},text(z,G){if(G)this.status=G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(z,{status:this.status,headers:this.headers})},send(z,G){if(G)this.status=G;let L=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),O=z instanceof Uint8Array?"Uint8Array":z instanceof ArrayBuffer?"ArrayBuffer":typeof z;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",L.get(O)??"text/plain; charset=utf-8");let $=O==="object"&&z!==null?JSON.stringify(z):z;return new Response($,{status:this.status,headers:this.headers})},json(z,G){if(G)this.status=G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(z,{status:this.status,headers:this.headers})},file(z,G,L){if(L)this.status=L;let O=Bun.file(z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",G??R(z));return new Response(O,{status:this.status,headers:this.headers})},async ejs(z,G={},L){if(L)this.status=L;let O;try{O=await import("ejs"),O=O.default||O}catch($){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let $=await Bun.file(z).text(),V=O.render($,G),W=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(V,{status:this.status,headers:W})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}},redirect(z,G){if(G)this.status=G;else this.status=302;return this.headers.set("Location",z),new Response(null,{status:this.status,headers:this.headers})},stream(z){let G=new Headers(this.headers),L=new ReadableStream({async start(O){await z(O),O.close()}});return new Response(L,{headers:G})},yieldStream(z){return new Response({async*[Symbol.asyncIterator](){yield*z()}},{headers:this.headers})},setCookie(z,G,L={}){let O=`${encodeURIComponent(z)}=${encodeURIComponent(G)}`;if(L.maxAge)O+=`; Max-Age=${L.maxAge}`;if(L.expires)O+=`; Expires=${L.expires.toUTCString()}`;if(L.path)O+=`; Path=${L.path}`;if(L.domain)O+=`; Domain=${L.domain}`;if(L.secure)O+="; Secure";if(L.httpOnly)O+="; HttpOnly";if(L.sameSite)O+=`; SameSite=${L.sameSite}`;return this.headers.append("Set-Cookie",O),this},get cookies(){if(!Z){let z=this.req.headers.get("cookie");Z=z?D(z):{}}return Z}}}function D(E){return Object.fromEntries(E.split(";").map((X)=>{let[K,...A]=X.trim().split("=");return[K,decodeURIComponent(A.join("="))]}))}function f(E,X){let K={},A=E.split("/"),[F]=X.split("?"),Z=F.split("/");if(A.length!==Z.length)return null;for(let Y=0;Y<A.length;Y++)if(A[Y].startsWith(":"))K[A[Y].slice(1)]=Z[Y];return K}async function b(E){let X=E.headers.get("Content-Type");if(!X)return{};if(E.headers.get("Content-Length")==="0"||!E.body)return{};try{if(X.startsWith("application/json"))return await E.json();if(X.startsWith("application/x-www-form-urlencoded")){let A=await E.text();return Object.fromEntries(new URLSearchParams(A))}if(X.startsWith("multipart/form-data")){let A=await E.formData(),F={};for(let[Z,Y]of A.entries())F[Z]=Y;return F}return{error:"Unknown request body type"}}catch(A){return{error:"Invalid request body format"}}}export{U as default};
@@ -1,6 +1,6 @@
1
- import { Server } from "bun";
1
+ import { BunRequest, Server } from "bun";
2
2
  import type { ContextType, DieselT } from "./types";
3
- export default function handleRequest(req: Request, server: Server, url: URL, diesel: DieselT): Promise<any>;
3
+ export default function handleRequest(req: BunRequest, server: Server, url: URL, diesel: DieselT): Promise<any>;
4
4
  export declare function handleFilterRequest(diesel: DieselT, path: string, ctx: ContextType, server: Server): Promise<Response | undefined>;
5
5
  export declare function generateErrorResponse(status: number, message: string): Response;
6
6
  export declare function handleStaticFiles(diesel: DieselT, pathname: string, ctx: ContextType): Promise<Response | null>;
@@ -1 +1 @@
1
- var L=Object.create;var{getPrototypeOf:O,defineProperty:m,getOwnPropertyNames:b}=Object;var u=Object.prototype.hasOwnProperty;var z=(f,R,o)=>{o=f!=null?L(O(f)):{};let n=R||!f||!f.__esModule?m(o,"default",{value:f,enumerable:!0}):o;for(let l of b(f))if(!u.call(n,l))m(n,l,{get:()=>f[l],enumerable:!0});return n};var G=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(R,o)=>(typeof require!=="undefined"?require:R)[o]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});function E(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function J(f,R){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(o)=>{try{let n=o.cookies?.accessToken||o.req?.headers?.get("Authorization");if(!n)return o.json({message:"Unauthorized: No token provided"},401);if(n.startsWith("Bearer "))n=n.slice(7);let l=f?.verify(n,R);if(!l)return o.json({message:"Unauthorized: Invalid token"},401);o.set("user",l);return}catch(n){return o.json({message:"Unauthorized: Invalid token",error:n?.message},401)}}}function W(f,R,o){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!R)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(n)=>{try{let l=n.cookies?.accessToken||n.req?.headers?.get("Authorization");if(!l)return n.json({message:"Unauthorized: No token provided"},401);if(l.startsWith("Bearer "))l=l.slice(7);let i=f?.verify(l,o);if(!i)return n.json({message:"Unauthorized: Invalid token"},401);let A=await R.findById(i._id).select("-password -refreshToken");if(!A)return n.json({message:"Unauthorized: User not found"},401);n.set("user",A);return}catch(l){return n.json({message:"Unauthorized: Authentication failed",error:l?.message},401)}}}function N(f,R,o){let n=null,l=null,i=null,A=null,w={};return{req:f,server:R,url:o,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(r,h){return this.headers.set(r,h),this},removeHeader(r){return this.headers.delete(r),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!n)try{n=Object.fromEntries(this.url.searchParams)}catch(r){throw new Error("Failed to parse query parameters")}return n},get params(){if(!l&&this.req.routePattern)try{l=K(this.req.routePattern,this.url.pathname)}catch(r){throw new Error("Failed to extract route parameters")}return l??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!A)A=(async()=>{let r=await X(this.req);if(r.error)throw new Error(r.error);return Object.keys(r).length===0?null:r})();return A},set(r,h){return w[r]=h,this},get(r){return w[r]},text(r,h){if(h)this.status=h;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(r,{status:this.status,headers:this.headers})},send(r,h){if(h)this.status=h;let F=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),g=r instanceof Uint8Array?"Uint8Array":r instanceof ArrayBuffer?"ArrayBuffer":typeof r;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",F.get(g)??"text/plain; charset=utf-8");let H=g==="object"&&r!==null?JSON.stringify(r):r;return new Response(H,{status:this.status,headers:this.headers})},json(r,h){if(h)this.status=h;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(r),{status:this.status,headers:this.headers})},file(r,h,F){if(F)this.status=F;let g=Bun.file(r);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",h??E(r));return new Response(g,{status:this.status,headers:this.headers})},async ejs(r,h={},F){if(F)this.status=F;let g;try{g=await import("ejs"),g=g.default||g}catch(H){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let H=await Bun.file(r).text(),$=g.render(H,h),T=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response($,{status:this.status,headers:T})}catch(H){return console.error("EJS Rendering Error:",H),new Response("Error rendering template",{status:500})}},redirect(r,h){if(h)this.status=h;else this.status=302;return this.headers.set("Location",r),new Response(null,{status:this.status,headers:this.headers})},setCookie(r,h,F={}){let g=`${encodeURIComponent(r)}=${encodeURIComponent(h)}`;if(F.maxAge)g+=`; Max-Age=${F.maxAge}`;if(F.expires)g+=`; Expires=${F.expires.toUTCString()}`;if(F.path)g+=`; Path=${F.path}`;if(F.domain)g+=`; Domain=${F.domain}`;if(F.secure)g+="; Secure";if(F.httpOnly)g+="; HttpOnly";if(F.sameSite)g+=`; SameSite=${F.sameSite}`;return this.headers.append("Set-Cookie",g),this},get cookies(){if(!i){let r=this.req.headers.get("cookie");i=r?I(r):{}}return i}}}function I(f){return Object.fromEntries(f.split(";").map((R)=>{let[o,...n]=R.trim().split("=");return[o,decodeURIComponent(n.join("="))]}))}function K(f,R){let o={},n=f.split("/"),[l]=R.split("?"),i=l.split("/");if(n.length!==i.length)return null;for(let A=0;A<n.length;A++)if(n[A].startsWith(":"))o[n[A].slice(1)]=i[A];return o}async function X(f){let R=f.headers.get("Content-Type");if(!R)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};try{if(R.startsWith("application/json"))return await f.json();if(R.startsWith("application/x-www-form-urlencoded")){let n=await f.text();return Object.fromEntries(new URLSearchParams(n))}if(R.startsWith("multipart/form-data")){let n=await f.formData(),l={};for(let[i,A]of n.entries())l[i]=A;return l}return{error:"Unknown request body type"}}catch(n){return{error:"Invalid request body format"}}}async function Y(f,R,o,n){let l=N(f,R,o),i=n.trie.search(o.pathname,f.method);f.routePattern=i?.path;try{if(n.hasFilterEnabled){let r=f.routePattern??o.pathname,h=await Z(n,r,l,R);if(h)return h}if(n.hasMiddleware){if(n.globalMiddlewares.length){let h=await C(n.globalMiddlewares,l,R);if(h)return h}let r=n.middlewares.get(o.pathname)||[];if(r?.length){let h=await C(r,l,R);if(h)return h}}if(!i?.handler||i.method!==f.method){if(n.staticPath){let r=await V(n,o.pathname,l);if(r)return r;let h=n.trie.search("*",f.method);if(h?.handler)return await h.handler(l)}if(n.hooks.routeNotFound?.length&&Array.isArray(n.hooks.routeNotFound)&&!i?.handler){let r=n.hooks.routeNotFound;for(let h=0;h<r.length;h++){let F=await r[h](l);if(F)return F}}if(!i||!i?.handler?.length)return M(404,`Route not found for ${o.pathname}`);if(i?.method!==f.method)return M(405,"Method not allowed")}if(n.hooks.preHandler?.length&&Array.isArray(n.hooks.preHandler)){let r=n.hooks.preHandler;for(let h=0;h<r.length;h++){let F=await r[h](l);if(F)return F}}let A=i.handler(l),w=A instanceof Promise?await A:A;if(n.hooks.onSend?.length&&Array.isArray(n.hooks.onSend)){let r=n.hooks.onSend;for(let h=0;h<r.length;h++){let F=await r[h](l);if(F)return F}}return w??M(204,"No response from this handler")}catch(A){return n.hooks.onError?.length&&Array.isArray(n.hooks.onError)?n.hooks.onError[0](A,f,o,R):M(500,"Internal Server Error")}finally{if(n.hooks.postHandler?.length&&Array.isArray(n.hooks.postHandler)){let A=n.hooks.postHandler;for(let w=0;w<A.length;w++){let r=await A[w](l);if(r)return r}}}}async function C(f,R,o){for(let n of f){let l=await n(R,o);if(l)return l}return null}async function Z(f,R,o,n){if(!f.filters.has(R))if(f.filterFunction.length)for(let l of f.filterFunction){let i=await l(o,n);if(i)return i}else return o.json({error:!0,message:"Protected route, authentication required",status:401},401)}function M(f,R){return new Response(JSON.stringify({error:!0,message:R,status:f}),{status:f,headers:{"Content-Type":"application/json"}})}async function V(f,R,o){if(!f.staticPath)return null;let n=`${f.staticPath}${R}`;if(await Bun.file(n).exists()){let i=E(n);return o.file(n,i,200)}return null}export{V as handleStaticFiles,Z as handleFilterRequest,M as generateErrorResponse,Y as default};
1
+ var T=Object.create;var{getPrototypeOf:L,defineProperty:N,getOwnPropertyNames:O}=Object;var z=Object.prototype.hasOwnProperty;var G=(r,o,l)=>{l=r!=null?T(L(r)):{};let n=o||!r||!r.__esModule?N(l,"default",{value:r,enumerable:!0}):l;for(let R of O(r))if(!z.call(n,R))N(n,R,{get:()=>r[R],enumerable:!0});return n};var I=((r)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(r,{get:(o,l)=>(typeof require!=="undefined"?require:o)[l]}):r)(function(r){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function g(r){switch(r.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function J(r,o){if(!r)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(l)=>{try{let n=l.cookies?.accessToken||l.req?.headers?.get("Authorization");if(!n)return l.json({message:"Unauthorized: No token provided"},401);if(n.startsWith("Bearer "))n=n.slice(7);let R=r?.verify(n,o);if(!R)return l.json({message:"Unauthorized: Invalid token"},401);l.set("user",R)}catch(n){return console.error("JWT verification error:",n),l.json({message:"Unauthorized: Invalid token",error:n?.message},401)}}}function D(r,o,l){if(!r)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!o)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(n)=>{try{let R=n.cookies?.accessToken||n.req?.headers?.get("Authorization");if(!R)return n.json({message:"Unauthorized: No token provided"},401);if(R.startsWith("Bearer "))R=R.slice(7);let F=r?.verify(R,l);if(!F)return n.json({message:"Unauthorized: Invalid token"},401);let A=await o.findById(F._id).select("-password -refreshToken");if(!A)return n.json({message:"Unauthorized: User not found"},401);n.set("user",A);return}catch(R){return n.json({message:"Unauthorized: Authentication failed",error:R?.message},401)}}}function H(r,o,l){let n=null,R=null,F=null,A=null,w={};return{req:r,server:o,url:l,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,h){return this.headers.set(f,h),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!n)try{n=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return n},get params(){if(!R&&this.req.routePattern)try{R=X(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return R??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!A)A=(async()=>{let f=await Y(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return A},set(f,h){return w[f]=h,this},get(f){return w[f]},text(f,h){if(h)this.status=h;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,h){if(h)this.status=h;let i=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),E=f instanceof Uint8Array?"Uint8Array":f instanceof ArrayBuffer?"ArrayBuffer":typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",i.get(E)??"text/plain; charset=utf-8");let M=E==="object"&&f!==null?JSON.stringify(f):f;return new Response(M,{status:this.status,headers:this.headers})},json(f,h){if(h)this.status=h;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,h,i){if(i)this.status=i;let E=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",h??g(f));return new Response(E,{status:this.status,headers:this.headers})},async ejs(f,h={},i){if(i)this.status=i;let E;try{E=await import("ejs"),E=E.default||E}catch(M){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let M=await Bun.file(f).text(),$=E.render(M,h),m=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response($,{status:this.status,headers:m})}catch(M){return console.error("EJS Rendering Error:",M),new Response("Error rendering template",{status:500})}},redirect(f,h){if(h)this.status=h;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let h=new Headers(this.headers),i=new ReadableStream({async start(E){await f(E),E.close()}});return new Response(i,{headers:h})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,h,i={}){let E=`${encodeURIComponent(f)}=${encodeURIComponent(h)}`;if(i.maxAge)E+=`; Max-Age=${i.maxAge}`;if(i.expires)E+=`; Expires=${i.expires.toUTCString()}`;if(i.path)E+=`; Path=${i.path}`;if(i.domain)E+=`; Domain=${i.domain}`;if(i.secure)E+="; Secure";if(i.httpOnly)E+="; HttpOnly";if(i.sameSite)E+=`; SameSite=${i.sameSite}`;return this.headers.append("Set-Cookie",E),this},get cookies(){if(!F){let f=this.req.headers.get("cookie");F=f?K(f):{}}return F}}}function K(r){return Object.fromEntries(r.split(";").map((o)=>{let[l,...n]=o.trim().split("=");return[l,decodeURIComponent(n.join("="))]}))}function X(r,o){let l={},n=r.split("/"),[R]=o.split("?"),F=R.split("/");if(n.length!==F.length)return null;for(let A=0;A<n.length;A++)if(n[A].startsWith(":"))l[n[A].slice(1)]=F[A];return l}async function Y(r){let o=r.headers.get("Content-Type");if(!o)return{};if(r.headers.get("Content-Length")==="0"||!r.body)return{};try{if(o.startsWith("application/json"))return await r.json();if(o.startsWith("application/x-www-form-urlencoded")){let n=await r.text();return Object.fromEntries(new URLSearchParams(n))}if(o.startsWith("multipart/form-data")){let n=await r.formData(),R={};for(let[F,A]of n.entries())R[F]=A;return R}return{error:"Unknown request body type"}}catch(n){return{error:"Invalid request body format"}}}async function Z(r,o,l,n){let R=H(r,o,l),F=n.trie.search(l.pathname,r.method);r.routePattern=F?.path;try{if(l.pathname.startsWith("/favicon"))return;if(n.hasFilterEnabled){let f=r.routePattern??l.pathname,h=await V(n,f,R,o);if(h)return h}if(n.hasMiddleware){if(n.globalMiddlewares.length){let h=await C(n.globalMiddlewares,R,o);if(h)return h}let f=n.middlewares.get(l.pathname)||[];if(f?.length){let h=await C(f,R,o);if(h)return h}}if(!F?.handler||F.method!==r.method){if(n.staticPath){let f=await W(n,l.pathname,R);if(f)return f;let h=n.trie.search("*",r.method);if(h?.handler)return await h.handler(R)}if(n.hooks.routeNotFound&&Array.isArray(n.hooks.routeNotFound)&&!F?.handler){let f=n.hooks.routeNotFound;for(let h=0;h<f.length;h++){let i=await f[h](R);if(i)return i}}if(!F||!F?.handler?.length)return u(404,`Route not found for ${l.pathname}`);if(F?.method!==r.method)return u(405,"Method not allowed")}if(n.hooks.preHandler?.length&&Array.isArray(n.hooks.preHandler)){let f=n.hooks.preHandler;for(let h=0;h<f.length;h++){let i=await f[h](R);if(i)return i}}let A=F.handler(R);return(A instanceof Promise?await A:A)??u(204,"")}catch(A){if(n.hooks.onError&&Array.isArray(n.hooks.onError)){let w=n.hooks.onError;for(let f=0;f<w.length;f++){let h=n.hooks.onError[f](A,r,l,o);if(h)return h}}return u(500,"Internal Server Error")}finally{if(n.hooks.onSend&&Array.isArray(n.hooks.onSend)){let A=n.hooks.onSend;for(let w=0;w<A.length;w++){let f=await A[w](R);if(f)return f}}}}async function C(r,o,l){for(let n of r){let R=await n(o,l);if(R)return R}return null}async function V(r,o,l,n){if(!r.filters.has(o))if(r.filterFunction.length)for(let R of r.filterFunction){let F=await R(l,n);if(F)return F}else return l.json({error:!0,message:"Protected route, authentication required",status:401},401)}function u(r,o){return new Response(JSON.stringify({error:!0,message:o,status:r}),{status:r,headers:{"Content-Type":"application/json"}})}async function W(r,o,l){if(!r.staticPath)return null;let n=`${r.staticPath}${o}`;if(await Bun.file(n).exists()){let F=g(n);return l.file(n,F,200)}return null}export{W as handleStaticFiles,V as handleFilterRequest,u as generateErrorResponse,Z as default};
package/dist/main.d.ts CHANGED
@@ -24,10 +24,12 @@ export default class Diesel {
24
24
  private user_jwt_secret;
25
25
  private baseApiUrl;
26
26
  private enableFileRouter;
27
- constructor({ jwtSecret, baseApiUrl, enableFileRouting }?: {
27
+ idleTimeOut: number;
28
+ constructor({ jwtSecret, baseApiUrl, enableFileRouting, idleTimeOut, }?: {
28
29
  jwtSecret?: string;
29
30
  baseApiUrl?: string;
30
31
  enableFileRouting?: boolean;
32
+ idleTimeOut?: number;
31
33
  });
32
34
  setupFilter(): FilterMethods;
33
35
  redirect(incomingPath: string, redirectPath: string, statusCode?: 302): this;
package/dist/main.js CHANGED
@@ -1,3 +1,3 @@
1
- var j=Object.create;var{getPrototypeOf:q,defineProperty:Z,getOwnPropertyNames:k}=Object;var P=Object.prototype.hasOwnProperty;var e=(n,r,f)=>{f=n!=null?j(q(n)):{};let g=r||!n||!n.__esModule?Z(f,"default",{value:n,enumerable:!0}):f;for(let u of k(n))if(!P.call(g,u))Z(g,u,{get:()=>n[u],enumerable:!0});return g};var h=((n)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(n,{get:(r,f)=>(typeof require!=="undefined"?require:r)[f]}):n)(function(n){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class D{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class t{root;constructor(){this.root=new D}insert(n,r){let f=this.root,g=n.split("/").filter(Boolean);if(n==="/"){f.isEndOfWord=!0,f.handler.push(r.handler),f.path=n,f.method.push(r.method);return}for(let u of g){let C=!1,o=u;if(u.startsWith(":"))C=!0,o=":";if(!f.children[o])f.children[o]=new D;f=f.children[o],f.isDynamic=C,f.pattern=u}f.isEndOfWord=!0,f.path=n,f.method.push(r.method),f.handler.push(r.handler)}search(n,r){let f=this.root,g=n.split("/").filter(Boolean),u=g.length;for(let m of g){let i=m;if(!f.children[i])if(f.children[":"])f=f.children[":"];else return null;else f=f.children[i]}let C=f.path.split("/").filter(Boolean);if(u!==C.length)return null;let o=f.method.indexOf(r);if(o!==-1)return{path:f.path,handler:f.handler[o],isDynamic:f.isDynamic,pattern:f.pattern,method:f.method[o]};return{path:f.path,handler:f.handler,isDynamic:f.isDynamic,pattern:f.pattern,method:f.method[o]}}}function O(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"}}function U(n,r){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(f)=>{try{let g=f.cookies?.accessToken||f.req?.headers?.get("Authorization");if(!g)return f.json({message:"Unauthorized: No token provided"},401);if(g.startsWith("Bearer "))g=g.slice(7);let u=n?.verify(g,r);if(!u)return f.json({message:"Unauthorized: Invalid token"},401);f.set("user",u);return}catch(g){return f.json({message:"Unauthorized: Invalid token",error:g?.message},401)}}}function V(n,r,f){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!r)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(g)=>{try{let u=g.cookies?.accessToken||g.req?.headers?.get("Authorization");if(!u)return g.json({message:"Unauthorized: No token provided"},401);if(u.startsWith("Bearer "))u=u.slice(7);let C=n?.verify(u,f);if(!C)return g.json({message:"Unauthorized: Invalid token"},401);let o=await r.findById(C._id).select("-password -refreshToken");if(!o)return g.json({message:"Unauthorized: User not found"},401);g.set("user",o);return}catch(u){return g.json({message:"Unauthorized: Authentication failed",error:u?.message},401)}}}function G(n,r,f){let g=null,u=null,C=null,o=null,m={};return{req:n,server:r,url:f,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(i,v){return this.headers.set(i,v),this},removeHeader(i){return this.headers.delete(i),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!g)try{g=Object.fromEntries(this.url.searchParams)}catch(i){throw new Error("Failed to parse query parameters")}return g},get params(){if(!u&&this.req.routePattern)try{u=d(this.req.routePattern,this.url.pathname)}catch(i){throw new Error("Failed to extract route parameters")}return u??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!o)o=(async()=>{let i=await a(this.req);if(i.error)throw new Error(i.error);return Object.keys(i).length===0?null:i})();return o},set(i,v){return m[i]=v,this},get(i){return m[i]},text(i,v){if(v)this.status=v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(i,{status:this.status,headers:this.headers})},send(i,v){if(v)this.status=v;let b=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),A=i instanceof Uint8Array?"Uint8Array":i instanceof ArrayBuffer?"ArrayBuffer":typeof i;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",b.get(A)??"text/plain; charset=utf-8");let $=A==="object"&&i!==null?JSON.stringify(i):i;return new Response($,{status:this.status,headers:this.headers})},json(i,v){if(v)this.status=v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(i),{status:this.status,headers:this.headers})},file(i,v,b){if(b)this.status=b;let A=Bun.file(i);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",v??O(i));return new Response(A,{status:this.status,headers:this.headers})},async ejs(i,v={},b){if(b)this.status=b;let A;try{A=await import("ejs"),A=A.default||A}catch($){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let $=await Bun.file(i).text(),c=A.render($,v),y=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(c,{status:this.status,headers:y})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}},redirect(i,v){if(v)this.status=v;else this.status=302;return this.headers.set("Location",i),new Response(null,{status:this.status,headers:this.headers})},setCookie(i,v,b={}){let A=`${encodeURIComponent(i)}=${encodeURIComponent(v)}`;if(b.maxAge)A+=`; Max-Age=${b.maxAge}`;if(b.expires)A+=`; Expires=${b.expires.toUTCString()}`;if(b.path)A+=`; Path=${b.path}`;if(b.domain)A+=`; Domain=${b.domain}`;if(b.secure)A+="; Secure";if(b.httpOnly)A+="; HttpOnly";if(b.sameSite)A+=`; SameSite=${b.sameSite}`;return this.headers.append("Set-Cookie",A),this},get cookies(){if(!C){let i=this.req.headers.get("cookie");C=i?p(i):{}}return C}}}function p(n){return Object.fromEntries(n.split(";").map((r)=>{let[f,...g]=r.trim().split("=");return[f,decodeURIComponent(g.join("="))]}))}function d(n,r){let f={},g=n.split("/"),[u]=r.split("?"),C=u.split("/");if(g.length!==C.length)return null;for(let o=0;o<g.length;o++)if(g[o].startsWith(":"))f[g[o].slice(1)]=C[o];return f}async function a(n){let r=n.headers.get("Content-Type");if(!r)return{};if(n.headers.get("Content-Length")==="0"||!n.body)return{};try{if(r.startsWith("application/json"))return await n.json();if(r.startsWith("application/x-www-form-urlencoded")){let g=await n.text();return Object.fromEntries(new URLSearchParams(g))}if(r.startsWith("multipart/form-data")){let g=await n.formData(),u={};for(let[C,o]of g.entries())u[C]=o;return u}return{error:"Unknown request body type"}}catch(g){return{error:"Invalid request body format"}}}async function R(n,r,f,g){let u=G(n,r,f),C=g.trie.search(f.pathname,n.method);n.routePattern=C?.path;try{if(g.hasFilterEnabled){let i=n.routePattern??f.pathname,v=await nn(g,i,u,r);if(v)return v}if(g.hasMiddleware){if(g.globalMiddlewares.length){let v=await s(g.globalMiddlewares,u,r);if(v)return v}let i=g.middlewares.get(f.pathname)||[];if(i?.length){let v=await s(i,u,r);if(v)return v}}if(!C?.handler||C.method!==n.method){if(g.staticPath){let i=await rn(g,f.pathname,u);if(i)return i;let v=g.trie.search("*",n.method);if(v?.handler)return await v.handler(u)}if(g.hooks.routeNotFound?.length&&Array.isArray(g.hooks.routeNotFound)&&!C?.handler){let i=g.hooks.routeNotFound;for(let v=0;v<i.length;v++){let b=await i[v](u);if(b)return b}}if(!C||!C?.handler?.length)return l(404,`Route not found for ${f.pathname}`);if(C?.method!==n.method)return l(405,"Method not allowed")}if(g.hooks.preHandler?.length&&Array.isArray(g.hooks.preHandler)){let i=g.hooks.preHandler;for(let v=0;v<i.length;v++){let b=await i[v](u);if(b)return b}}let o=C.handler(u),m=o instanceof Promise?await o:o;if(g.hooks.onSend?.length&&Array.isArray(g.hooks.onSend)){let i=g.hooks.onSend;for(let v=0;v<i.length;v++){let b=await i[v](u);if(b)return b}}return m??l(204,"No response from this handler")}catch(o){return g.hooks.onError?.length&&Array.isArray(g.hooks.onError)?g.hooks.onError[0](o,n,f,r):l(500,"Internal Server Error")}finally{if(g.hooks.postHandler?.length&&Array.isArray(g.hooks.postHandler)){let o=g.hooks.postHandler;for(let m=0;m<o.length;m++){let i=await o[m](u);if(i)return i}}}}async function s(n,r,f){for(let g of n){let u=await g(r,f);if(u)return u}return null}async function nn(n,r,f,g){if(!n.filters.has(r))if(n.filterFunction.length)for(let u of n.filterFunction){let C=await u(f,g);if(C)return C}else return f.json({error:!0,message:"Protected route, authentication required",status:401},401)}function l(n,r){return new Response(JSON.stringify({error:!0,message:r,status:n}),{status:n,headers:{"Content-Type":"application/json"}})}async function rn(n,r,f){if(!n.staticPath)return null;let g=`${n.staticPath}${r}`;if(await Bun.file(g).exists()){let C=O(g);return f.file(g,C,200)}return null}var{create:on,defineProperty:W,getOwnPropertyDescriptor:fn,getOwnPropertyNames:gn,getPrototypeOf:mn}=Object,vn=Object.prototype.hasOwnProperty,un=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports),An=(n,r,f,g)=>{if(r&&typeof r=="object"||typeof r=="function")for(let u of gn(r))!vn.call(n,u)&&u!==f&&W(n,u,{get:()=>r[u],enumerable:!(g=fn(r,u))||g.enumerable});return n},Cn=(n,r,f)=>(f=n!=null?on(mn(n)):{},An(r||!n||!n.__esModule?W(f,"default",{value:n,enumerable:!0}):f,n)),bn=un((n,r)=>{function f(o){if(typeof o!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(o))}function g(o,m){for(var i="",v=0,b=-1,A=0,$,c=0;c<=o.length;++c){if(c<o.length)$=o.charCodeAt(c);else{if($===47)break;$=47}if($===47){if(!(b===c-1||A===1))if(b!==c-1&&A===2){if(i.length<2||v!==2||i.charCodeAt(i.length-1)!==46||i.charCodeAt(i.length-2)!==46){if(i.length>2){var y=i.lastIndexOf("/");if(y!==i.length-1){y===-1?(i="",v=0):(i=i.slice(0,y),v=i.length-1-i.lastIndexOf("/")),b=c,A=0;continue}}else if(i.length===2||i.length===1){i="",v=0,b=c,A=0;continue}}m&&(i.length>0?i+="/..":i="..",v=2)}else i.length>0?i+="/"+o.slice(b+1,c):i=o.slice(b+1,c),v=c-b-1;b=c,A=0}else $===46&&A!==-1?++A:A=-1}return i}function u(o,m){var i=m.dir||m.root,v=m.base||(m.name||"")+(m.ext||"");return i?i===m.root?i+v:i+o+v:v}var C={resolve:function(){for(var o="",m=!1,i,v=arguments.length-1;v>=-1&&!m;v--){var b;v>=0?b=arguments[v]:(i===void 0&&(i=process.cwd()),b=i),f(b),b.length!==0&&(o=b+"/"+o,m=b.charCodeAt(0)===47)}return o=g(o,!m),m?o.length>0?"/"+o:"/":o.length>0?o:"."},normalize:function(o){if(f(o),o.length===0)return".";var m=o.charCodeAt(0)===47,i=o.charCodeAt(o.length-1)===47;return o=g(o,!m),o.length===0&&!m&&(o="."),o.length>0&&i&&(o+="/"),m?"/"+o:o},isAbsolute:function(o){return f(o),o.length>0&&o.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var o,m=0;m<arguments.length;++m){var i=arguments[m];f(i),i.length>0&&(o===void 0?o=i:o+="/"+i)}return o===void 0?".":C.normalize(o)},relative:function(o,m){if(f(o),f(m),o===m||(o=C.resolve(o),m=C.resolve(m),o===m))return"";for(var i=1;i<o.length&&o.charCodeAt(i)===47;++i);for(var v=o.length,b=v-i,A=1;A<m.length&&m.charCodeAt(A)===47;++A);for(var $=m.length,c=$-A,y=b<c?b:c,F=-1,L=0;L<=y;++L){if(L===y){if(c>y){if(m.charCodeAt(A+L)===47)return m.slice(A+L+1);if(L===0)return m.slice(A+L)}else b>y&&(o.charCodeAt(i+L)===47?F=L:L===0&&(F=0));break}var Y=o.charCodeAt(i+L),H=m.charCodeAt(A+L);if(Y!==H)break;Y===47&&(F=L)}var w="";for(L=i+F+1;L<=v;++L)(L===v||o.charCodeAt(L)===47)&&(w.length===0?w+="..":w+="/..");return w.length>0?w+m.slice(A+F):(A+=F,m.charCodeAt(A)===47&&++A,m.slice(A))},_makeLong:function(o){return o},dirname:function(o){if(f(o),o.length===0)return".";for(var m=o.charCodeAt(0),i=m===47,v=-1,b=!0,A=o.length-1;A>=1;--A)if(m=o.charCodeAt(A),m===47){if(!b){v=A;break}}else b=!1;return v===-1?i?"/":".":i&&v===1?"//":o.slice(0,v)},basename:function(o,m){if(m!==void 0&&typeof m!="string")throw new TypeError('"ext" argument must be a string');f(o);var i=0,v=-1,b=!0,A;if(m!==void 0&&m.length>0&&m.length<=o.length){if(m.length===o.length&&m===o)return"";var $=m.length-1,c=-1;for(A=o.length-1;A>=0;--A){var y=o.charCodeAt(A);if(y===47){if(!b){i=A+1;break}}else c===-1&&(b=!1,c=A+1),$>=0&&(y===m.charCodeAt($)?--$===-1&&(v=A):($=-1,v=c))}return i===v?v=c:v===-1&&(v=o.length),o.slice(i,v)}else{for(A=o.length-1;A>=0;--A)if(o.charCodeAt(A)===47){if(!b){i=A+1;break}}else v===-1&&(b=!1,v=A+1);return v===-1?"":o.slice(i,v)}},extname:function(o){f(o);for(var m=-1,i=0,v=-1,b=!0,A=0,$=o.length-1;$>=0;--$){var c=o.charCodeAt($);if(c===47){if(!b){i=$+1;break}continue}v===-1&&(b=!1,v=$+1),c===46?m===-1?m=$:A!==1&&(A=1):m!==-1&&(A=-1)}return m===-1||v===-1||A===0||A===1&&m===v-1&&m===i+1?"":o.slice(m,v)},format:function(o){if(o===null||typeof o!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof o);return u("/",o)},parse:function(o){f(o);var m={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return m;var i=o.charCodeAt(0),v=i===47,b;v?(m.root="/",b=1):b=0;for(var A=-1,$=0,c=-1,y=!0,F=o.length-1,L=0;F>=b;--F){if(i=o.charCodeAt(F),i===47){if(!y){$=F+1;break}continue}c===-1&&(y=!1,c=F+1),i===46?A===-1?A=F:L!==1&&(L=1):A!==-1&&(L=-1)}return A===-1||c===-1||L===0||L===1&&A===c-1&&A===$+1?c!==-1&&($===0&&v?m.base=m.name=o.slice(1,c):m.base=m.name=o.slice($,c)):($===0&&v?(m.name=o.slice(1,A),m.base=o.slice(1,c)):(m.name=o.slice($,A),m.base=o.slice($,c)),m.ext=o.slice(A,c)),$>0?m.dir=o.slice(0,$-1):v&&(m.dir="/"),m},sep:"/",delimiter:":",win32:null,posix:null};C.posix=C,r.exports=C}),I=Cn(bn()),E=I,cn=I,J=function(n){return n},S=function(){throw new Error("Not implemented")};E.parse??=S;cn.parse??=S;var T={resolve:E.resolve.bind(E),normalize:E.normalize.bind(E),isAbsolute:E.isAbsolute.bind(E),join:E.join.bind(E),relative:E.relative.bind(E),toNamespacedPath:J,dirname:E.dirname.bind(E),basename:E.basename.bind(E),extname:E.extname.bind(E),format:E.format.bind(E),parse:E.parse.bind(E),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:J},M={sep:"\\",delimiter:";",win32:void 0,...T,posix:T};T.win32=M.win32=M;T.posix=T;var z=T;var{default:X}=(()=>({}));var N={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},K=(n,r,f)=>{let g=N[n]||N.reset,u=f?.method?N.method[f.method]||N.reset:N.reset;console.log(`
2
- ${g}[${n.toUpperCase()}]${N.reset} ${r} - ${u}${f?.method||""}${N.reset}`),console.log(JSON.stringify({timestamp:new Date().toISOString(),...f},null,2)+`
3
- `)},B=(n)=>{n.addHooks("onRequest",async(r,f)=>{r.startTime=Date.now(),K("info","Incoming Request",{method:r.method,url:f.toString(),headers:{"user-agent":r.headers.get("user-agent"),"content-type":r.headers.get("Content-Type")}})}),n.addHooks("postHandler",(r)=>{let f=`${Date.now()-r.req.startTime}ms`;K("info","Response Sent",{method:r.req.method,url:r.url,status:r.status,duration:f,headers:{"content-type":r.headers.get("Content-Type")}})})},x=(n,r,f,g=0,u)=>{let C=n==="<--"?`${n} ${r} ${f}`:`${n} ${r} ${f} ${g} ${u||""}`;console.log(C)},$n=(n)=>{let r=Date.now()-n;return r<1000?`${r}ms`:`${Math.round(r/1000)}s`},Q=(n)=>{n.addHooks("onRequest",(r,f)=>{r.startTime=Date.now(),x("<--",r.method,new URL(f).pathname)}),n.addHooks("postHandler",async(r)=>{let{method:f,url:g}=r.req,u=new URL(g).pathname;x("-->",f,u,r.status,$n(r.req.startTime))}),n.addHooks("routeNotFound",(r)=>{x("routeNotFound",r.req.method,r.url.pathname,404)}),n.addHooks("onError",(r,f,g)=>{K("error","Error occurred",{method:f.method,url:g.toString()})})};class _{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;constructor({jwtSecret:n,baseApiUrl:r,enableFileRouting:f}={}){this.enableFileRouter=f??!1,this.baseApiUrl=r||"",this.user_jwt_secret=n||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new t,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[],routeNotFound:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...n)=>{return this.FilterRoutes=n,this.setupFilter()},permitAll:()=>{for(let n of this?.FilterRoutes)this.filters.add(n);return this.FilterRoutes=null,this.setupFilter()},authenticate:(n)=>{if(n?.length)for(let r of n)this.filterFunction.push(r)},authenticateJwt:(n)=>{this.filterFunction.push(U(n,this.user_jwt_secret))},authenticateJwtDB:(n,r)=>{this.filterFunction.push(V(n,r,this.user_jwt_secret))}}}redirect(n,r,f){return this.any(n,(g)=>{let u=g.params,C=r;if(u)for(let m in u)C=C.replace(`:${m}`,u[m]);let o=g.url.search;if(o)C+=o;return g.redirect(C,f)}),this}serveStatic(n){return this.staticPath=n,this}static(n){return this.staticFiles={...this.staticFiles,...n},this}addHooks(n,r){if(typeof n!=="string")throw new Error("hookName must be a string");if(typeof r!=="function")throw new Error("callback must be a instance of function");switch(n){case"onRequest":this.hooks.onRequest?.push(r);break;case"preHandler":this.hooks.preHandler?.push(r);break;case"postHandler":this.hooks.postHandler?.push(r);break;case"onSend":this.hooks.onSend?.push(r);break;case"onError":this.hooks.onError?.push(r);break;case"onClose":this.hooks.onClose?.push(r);break;case"routeNotFound":this.hooks.routeNotFound?.push(r);break;default:throw new Error(`Unknown hook type: ${n}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[n,r]of this.middlewares.entries())if(r.length>0){this.hasMiddleware=!0;break}if(this.enableFileRouter){let n=process.cwd(),r=z.join(n,"src","routes");if(X?.existsSync(r))this.loadRoutes(r,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(n,r,f){let g=await import(n),u;if(f===".ts")u=z.basename(n,".ts");else if(f===".js")u=z.basename(n,".js");let C=r+"/"+u;if(C.endsWith("/index"))C=r;else if(C.endsWith("/api"))C=r;C=C.replace(/\[(.*?)\]/g,":$1");let o=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let m of o)if(g[m]){let i=m,v=g[m];this[i.toLocaleLowerCase()](`${this.baseApiUrl}${C}`,v)}}async loadRoutes(n,r){let f=await X.promises.readdir(n);for(let g of f){let u=z.join(n,g);if((await X.promises.stat(u)).isDirectory())this.loadRoutes(u,r+"/"+g);else if(g.endsWith(".ts"))this.registerFileRoutes(u,r,".ts");else if(g.endsWith(".js"))this.registerFileRoutes(u,r,".js")}}useLogger(n){return Q(n),this}useAdvancedLogger(n){return B(n),this}listen(n,...r){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let f="0.0.0.0",g=void 0,u={};for(let o of r)if(typeof o==="string")f=o;else if(typeof o==="function")g=o;else if(typeof o==="object"&&o!==null)u=o;this.compile();let C={port:n,hostname:f,fetch:async(o,m)=>{let i=new URL(o.url);if(this.hooks.onRequest){let v=this.hooks.onRequest;for(let b=0;b<v.length;b++)await v[b](o,i,m)}return await R(o,m,i,this)},static:this.staticFiles,development:!0};if(u.sslCert&&u.sslKey)C.certFile=u.sslCert,C.keyFile=u.sslKey;if(this.serverInstance=Bun?.serve(C),u.sslCert&&u.sslKey)console.log(`HTTPS server is running on https://localhost:${n}`);if(g)return g();return this.serverInstance}close(n){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,n?n():console.log("Server has been stopped");else console.warn("Server is not running.")}route(n,r){if(!n||typeof n!=="string")throw new Error("Path must be a string");let f=Object.fromEntries(r.tempRoutes);return Object.entries(f).forEach(([u,C])=>{let o=u.replace(/::\w+$/,""),m=`${n}${o}`;if(!this.middlewares.has(m))this.middlewares.set(m,[]);C.handlers.slice(0,-1).forEach((A)=>{if(!this.middlewares.get(m)?.includes(A))this.middlewares.get(m)?.push(A)});let v=C.handlers[C.handlers.length-1],b=C.method;try{this.trie.insert(m,{handler:v,method:b})}catch(A){console.error(`Error inserting ${m}:`,A)}}),r=null,this}register(n,r){return this.route(n,r)}addRoute(n,r,f){if(typeof r!=="string")throw new Error(`Error in ${f[f.length-1]}: Path must be a string. Received: ${typeof r}`);if(typeof n!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof n}`);this.tempRoutes?.set(r+"::"+n,{method:n,handlers:f});let g=f.slice(0,-1),u=f[f.length-1];if(!this.middlewares.has(r))this.middlewares.set(r,[]);g.forEach((C)=>{if(r==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...g])];else if(!this.middlewares.get(r)?.includes(C))this.middlewares.get(r)?.push(C)});try{if(n==="ANY"){let C=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let o of C)this.trie.insert(r,{handler:u,method:o})}this.trie.insert(r,{handler:u,method:n})}catch(C){console.error(`Error inserting ${r}:`,C)}}use(n,r){if(Array.isArray(n))n.forEach((g)=>{if(typeof g==="function")this.globalMiddlewares.push(g)});if(typeof n==="function"){if(this.globalMiddlewares.push(n),Array.isArray(r))r.forEach((g)=>{this.globalMiddlewares.push(g)});return}return(Array.isArray(n)?n.filter((g)=>typeof g==="string"):[n].filter((g)=>typeof g==="string")).forEach((g)=>{if(!this.middlewares.has(g))this.middlewares.set(g,[]);if(r)(Array.isArray(r)?r:[r]).forEach((C)=>{this.middlewares.get(g)?.push(C)})}),this}get(n,...r){return this.addRoute("GET",n,r),this}post(n,...r){return this.addRoute("POST",n,r),this}put(n,...r){return this.addRoute("PUT",n,r),this}patch(n,...r){return this.addRoute("PATCH",n,r),this}delete(n,...r){return this.addRoute("DELETE",n,r),this}any(n,...r){return this.addRoute("ANY",n,r),this}head(n,...r){return this.addRoute("HEAD",n,r),this}options(n,...r){return this.addRoute("OPTIONS",n,r),this}propfind(n,...r){return this.addRoute("PROPFIND",n,r),this}}export{_ as default};
1
+ var q=Object.create;var{getPrototypeOf:l,defineProperty:X,getOwnPropertyNames:P}=Object;var k=Object.prototype.hasOwnProperty;var e=(n,o,r)=>{r=n!=null?q(l(n)):{};let g=o||!n||!n.__esModule?X(r,"default",{value:n,enumerable:!0}):r;for(let m of P(n))if(!k.call(g,m))X(g,m,{get:()=>n[m],enumerable:!0});return g};var h=((n)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(n,{get:(o,r)=>(typeof require!=="undefined"?require:o)[r]}):n)(function(n){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class x{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class T{root;constructor(){this.root=new x}insert(n,o){let r=this.root,g=n.split("/").filter(Boolean);if(n==="/"){r.isEndOfWord=!0,r.handler.push(o.handler),r.path=n,r.method.push(o.method);return}for(let m of g){let $=!1,i=m;if(m.startsWith(":"))$=!0,i=":";if(!r.children[i])r.children[i]=new x;r=r.children[i],r.isDynamic=$,r.pattern=m}r.isEndOfWord=!0,r.path=n,r.method.push(o.method),r.handler.push(o.handler)}search(n,o){let r=this.root,g=n.split("/").filter(Boolean),m=g.length;for(let u of g){let f=u;if(!r.children[f])if(r.children[":"])r=r.children[":"];else return null;else r=r.children[f]}let $=r.path.split("/").filter(Boolean);if(m!==$.length)return null;let i=r.method.indexOf(o);if(i!==-1)return{path:r.path,handler:r.handler[i],isDynamic:r.isDynamic,pattern:r.pattern,method:r.method[i]};return{path:r.path,handler:r.handler,isDynamic:r.isDynamic,pattern:r.pattern,method:r.method[i]}}}function z(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"}}function Y(n,o){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(r)=>{try{let g=r.cookies?.accessToken||r.req?.headers?.get("Authorization");if(!g)return r.json({message:"Unauthorized: No token provided"},401);if(g.startsWith("Bearer "))g=g.slice(7);let m=n?.verify(g,o);if(!m)return r.json({message:"Unauthorized: Invalid token"},401);r.set("user",m)}catch(g){return console.error("JWT verification error:",g),r.json({message:"Unauthorized: Invalid token",error:g?.message},401)}}}function Z(n,o,r){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!o)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(g)=>{try{let m=g.cookies?.accessToken||g.req?.headers?.get("Authorization");if(!m)return g.json({message:"Unauthorized: No token provided"},401);if(m.startsWith("Bearer "))m=m.slice(7);let $=n?.verify(m,r);if(!$)return g.json({message:"Unauthorized: Invalid token"},401);let i=await o.findById($._id).select("-password -refreshToken");if(!i)return g.json({message:"Unauthorized: User not found"},401);g.set("user",i);return}catch(m){return g.json({message:"Unauthorized: Authentication failed",error:m?.message},401)}}}function D(n,o,r){let g=null,m=null,$=null,i=null,u={};return{req:n,server:o,url:r,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,v){return this.headers.set(f,v),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!g)try{g=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return g},get params(){if(!m&&this.req.routePattern)try{m=d(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return m??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!i)i=(async()=>{let f=await a(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return i},set(f,v){return u[f]=v,this},get(f){return u[f]},text(f,v){if(v)this.status=v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,v){if(v)this.status=v;let A=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),C=f instanceof Uint8Array?"Uint8Array":f instanceof ArrayBuffer?"ArrayBuffer":typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",A.get(C)??"text/plain; charset=utf-8");let L=C==="object"&&f!==null?JSON.stringify(f):f;return new Response(L,{status:this.status,headers:this.headers})},json(f,v){if(v)this.status=v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,v,A){if(A)this.status=A;let C=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",v??z(f));return new Response(C,{status:this.status,headers:this.headers})},async ejs(f,v={},A){if(A)this.status=A;let C;try{C=await import("ejs"),C=C.default||C}catch(L){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let L=await Bun.file(f).text(),b=C.render(L,v),t=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(b,{status:this.status,headers:t})}catch(L){return console.error("EJS Rendering Error:",L),new Response("Error rendering template",{status:500})}},redirect(f,v){if(v)this.status=v;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let v=new Headers(this.headers),A=new ReadableStream({async start(C){await f(C),C.close()}});return new Response(A,{headers:v})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,v,A={}){let C=`${encodeURIComponent(f)}=${encodeURIComponent(v)}`;if(A.maxAge)C+=`; Max-Age=${A.maxAge}`;if(A.expires)C+=`; Expires=${A.expires.toUTCString()}`;if(A.path)C+=`; Path=${A.path}`;if(A.domain)C+=`; Domain=${A.domain}`;if(A.secure)C+="; Secure";if(A.httpOnly)C+="; HttpOnly";if(A.sameSite)C+=`; SameSite=${A.sameSite}`;return this.headers.append("Set-Cookie",C),this},get cookies(){if(!$){let f=this.req.headers.get("cookie");$=f?p(f):{}}return $}}}function p(n){return Object.fromEntries(n.split(";").map((o)=>{let[r,...g]=o.trim().split("=");return[r,decodeURIComponent(g.join("="))]}))}function d(n,o){let r={},g=n.split("/"),[m]=o.split("?"),$=m.split("/");if(g.length!==$.length)return null;for(let i=0;i<g.length;i++)if(g[i].startsWith(":"))r[g[i].slice(1)]=$[i];return r}async function a(n){let o=n.headers.get("Content-Type");if(!o)return{};if(n.headers.get("Content-Length")==="0"||!n.body)return{};try{if(o.startsWith("application/json"))return await n.json();if(o.startsWith("application/x-www-form-urlencoded")){let g=await n.text();return Object.fromEntries(new URLSearchParams(g))}if(o.startsWith("multipart/form-data")){let g=await n.formData(),m={};for(let[$,i]of g.entries())m[$]=i;return m}return{error:"Unknown request body type"}}catch(g){return{error:"Invalid request body format"}}}async function G(n,o,r,g){let m=D(n,o,r),$=g.trie.search(r.pathname,n.method);n.routePattern=$?.path;try{if(r.pathname.startsWith("/favicon"))return;if(g.hasFilterEnabled){let f=n.routePattern??r.pathname,v=await nn(g,f,m,o);if(v)return v}if(g.hasMiddleware){if(g.globalMiddlewares.length){let v=await M(g.globalMiddlewares,m,o);if(v)return v}let f=g.middlewares.get(r.pathname)||[];if(f?.length){let v=await M(f,m,o);if(v)return v}}if(!$?.handler||$.method!==n.method){if(g.staticPath){let f=await on(g,r.pathname,m);if(f)return f;let v=g.trie.search("*",n.method);if(v?.handler)return await v.handler(m)}if(g.hooks.routeNotFound&&Array.isArray(g.hooks.routeNotFound)&&!$?.handler){let f=g.hooks.routeNotFound;for(let v=0;v<f.length;v++){let A=await f[v](m);if(A)return A}}if(!$||!$?.handler?.length)return R(404,`Route not found for ${r.pathname}`);if($?.method!==n.method)return R(405,"Method not allowed")}if(g.hooks.preHandler?.length&&Array.isArray(g.hooks.preHandler)){let f=g.hooks.preHandler;for(let v=0;v<f.length;v++){let A=await f[v](m);if(A)return A}}let i=$.handler(m);return(i instanceof Promise?await i:i)??R(204,"")}catch(i){if(g.hooks.onError&&Array.isArray(g.hooks.onError)){let u=g.hooks.onError;for(let f=0;f<u.length;f++){let v=g.hooks.onError[f](i,n,r,o);if(v)return v}}return R(500,"Internal Server Error")}finally{if(g.hooks.onSend&&Array.isArray(g.hooks.onSend)){let i=g.hooks.onSend;for(let u=0;u<i.length;u++){let f=await i[u](m);if(f)return f}}}}async function M(n,o,r){for(let g of n){let m=await g(o,r);if(m)return m}return null}async function nn(n,o,r,g){if(!n.filters.has(o))if(n.filterFunction.length)for(let m of n.filterFunction){let $=await m(r,g);if($)return $}else return r.json({error:!0,message:"Protected route, authentication required",status:401},401)}function R(n,o){return new Response(JSON.stringify({error:!0,message:o,status:n}),{status:n,headers:{"Content-Type":"application/json"}})}async function on(n,o,r){if(!n.staticPath)return null;let g=`${n.staticPath}${o}`;if(await Bun.file(g).exists()){let $=z(g);return r.file(g,$,200)}return null}var{create:rn,defineProperty:W,getOwnPropertyDescriptor:fn,getOwnPropertyNames:gn,getPrototypeOf:un}=Object,vn=Object.prototype.hasOwnProperty,mn=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),Cn=(n,o,r,g)=>{if(o&&typeof o=="object"||typeof o=="function")for(let m of gn(o))!vn.call(n,m)&&m!==r&&W(n,m,{get:()=>o[m],enumerable:!(g=fn(o,m))||g.enumerable});return n},$n=(n,o,r)=>(r=n!=null?rn(un(n)):{},Cn(o||!n||!n.__esModule?W(r,"default",{value:n,enumerable:!0}):r,n)),An=mn((n,o)=>{function r(i){if(typeof i!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function g(i,u){for(var f="",v=0,A=-1,C=0,L,b=0;b<=i.length;++b){if(b<i.length)L=i.charCodeAt(b);else{if(L===47)break;L=47}if(L===47){if(!(A===b-1||C===1))if(A!==b-1&&C===2){if(f.length<2||v!==2||f.charCodeAt(f.length-1)!==46||f.charCodeAt(f.length-2)!==46){if(f.length>2){var t=f.lastIndexOf("/");if(t!==f.length-1){t===-1?(f="",v=0):(f=f.slice(0,t),v=f.length-1-f.lastIndexOf("/")),A=b,C=0;continue}}else if(f.length===2||f.length===1){f="",v=0,A=b,C=0;continue}}u&&(f.length>0?f+="/..":f="..",v=2)}else f.length>0?f+="/"+i.slice(A+1,b):f=i.slice(A+1,b),v=b-A-1;A=b,C=0}else L===46&&C!==-1?++C:C=-1}return f}function m(i,u){var f=u.dir||u.root,v=u.base||(u.name||"")+(u.ext||"");return f?f===u.root?f+v:f+i+v:v}var $={resolve:function(){for(var i="",u=!1,f,v=arguments.length-1;v>=-1&&!u;v--){var A;v>=0?A=arguments[v]:(f===void 0&&(f=process.cwd()),A=f),r(A),A.length!==0&&(i=A+"/"+i,u=A.charCodeAt(0)===47)}return i=g(i,!u),u?i.length>0?"/"+i:"/":i.length>0?i:"."},normalize:function(i){if(r(i),i.length===0)return".";var u=i.charCodeAt(0)===47,f=i.charCodeAt(i.length-1)===47;return i=g(i,!u),i.length===0&&!u&&(i="."),i.length>0&&f&&(i+="/"),u?"/"+i:i},isAbsolute:function(i){return r(i),i.length>0&&i.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var i,u=0;u<arguments.length;++u){var f=arguments[u];r(f),f.length>0&&(i===void 0?i=f:i+="/"+f)}return i===void 0?".":$.normalize(i)},relative:function(i,u){if(r(i),r(u),i===u||(i=$.resolve(i),u=$.resolve(u),i===u))return"";for(var f=1;f<i.length&&i.charCodeAt(f)===47;++f);for(var v=i.length,A=v-f,C=1;C<u.length&&u.charCodeAt(C)===47;++C);for(var L=u.length,b=L-C,t=A<b?A:b,y=-1,E=0;E<=t;++E){if(E===t){if(b>t){if(u.charCodeAt(C+E)===47)return u.slice(C+E+1);if(E===0)return u.slice(C+E)}else A>t&&(i.charCodeAt(f+E)===47?y=E:E===0&&(y=0));break}var S=i.charCodeAt(f+E),j=u.charCodeAt(C+E);if(S!==j)break;S===47&&(y=E)}var w="";for(E=f+y+1;E<=v;++E)(E===v||i.charCodeAt(E)===47)&&(w.length===0?w+="..":w+="/..");return w.length>0?w+u.slice(C+y):(C+=y,u.charCodeAt(C)===47&&++C,u.slice(C))},_makeLong:function(i){return i},dirname:function(i){if(r(i),i.length===0)return".";for(var u=i.charCodeAt(0),f=u===47,v=-1,A=!0,C=i.length-1;C>=1;--C)if(u=i.charCodeAt(C),u===47){if(!A){v=C;break}}else A=!1;return v===-1?f?"/":".":f&&v===1?"//":i.slice(0,v)},basename:function(i,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');r(i);var f=0,v=-1,A=!0,C;if(u!==void 0&&u.length>0&&u.length<=i.length){if(u.length===i.length&&u===i)return"";var L=u.length-1,b=-1;for(C=i.length-1;C>=0;--C){var t=i.charCodeAt(C);if(t===47){if(!A){f=C+1;break}}else b===-1&&(A=!1,b=C+1),L>=0&&(t===u.charCodeAt(L)?--L===-1&&(v=C):(L=-1,v=b))}return f===v?v=b:v===-1&&(v=i.length),i.slice(f,v)}else{for(C=i.length-1;C>=0;--C)if(i.charCodeAt(C)===47){if(!A){f=C+1;break}}else v===-1&&(A=!1,v=C+1);return v===-1?"":i.slice(f,v)}},extname:function(i){r(i);for(var u=-1,f=0,v=-1,A=!0,C=0,L=i.length-1;L>=0;--L){var b=i.charCodeAt(L);if(b===47){if(!A){f=L+1;break}continue}v===-1&&(A=!1,v=L+1),b===46?u===-1?u=L:C!==1&&(C=1):u!==-1&&(C=-1)}return u===-1||v===-1||C===0||C===1&&u===v-1&&u===f+1?"":i.slice(u,v)},format:function(i){if(i===null||typeof i!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return m("/",i)},parse:function(i){r(i);var u={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return u;var f=i.charCodeAt(0),v=f===47,A;v?(u.root="/",A=1):A=0;for(var C=-1,L=0,b=-1,t=!0,y=i.length-1,E=0;y>=A;--y){if(f=i.charCodeAt(y),f===47){if(!t){L=y+1;break}continue}b===-1&&(t=!1,b=y+1),f===46?C===-1?C=y:E!==1&&(E=1):C!==-1&&(E=-1)}return C===-1||b===-1||E===0||E===1&&C===b-1&&C===L+1?b!==-1&&(L===0&&v?u.base=u.name=i.slice(1,b):u.base=u.name=i.slice(L,b)):(L===0&&v?(u.name=i.slice(1,C),u.base=i.slice(1,b)):(u.name=i.slice(L,C),u.base=i.slice(L,b)),u.ext=i.slice(C,b)),L>0?u.dir=i.slice(0,L-1):v&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};$.posix=$,o.exports=$}),B=$n(An()),c=B,bn=B,U=function(n){return n},J=function(){throw new Error("Not implemented")};c.parse??=J;bn.parse??=J;var F={resolve:c.resolve.bind(c),normalize:c.normalize.bind(c),isAbsolute:c.isAbsolute.bind(c),join:c.join.bind(c),relative:c.relative.bind(c),toNamespacedPath:U,dirname:c.dirname.bind(c),basename:c.basename.bind(c),extname:c.extname.bind(c),format:c.format.bind(c),parse:c.parse.bind(c),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:U},V={sep:"\\",delimiter:";",win32:void 0,...F,posix:F};F.win32=V.win32=V;F.posix=F;var N=F;var{default:K}=(()=>({}));var s={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},I=(n,o,r)=>{let g=s[n]||s.reset,m=r?.method?s.method[r.method]||s.reset:s.reset,$=r?.status?r.status>=500?s.error:r.status>=400?s.warn:s.info:s.reset;console.log(`
2
+ ${g}[${n.toUpperCase()}]${s.reset} ${o} - ${m}${r?.method||""}${s.reset}`);let i={timestamp:new Date().toISOString(),...r,status:r?.status?`${$}${r.status}${s.reset}`:void 0,method:r?.method?`${m}${r.method}${s.reset}`:void 0};console.log(JSON.stringify(i,null,2)+`
3
+ `)},Q=(n)=>{n.addHooks("onRequest",async(o,r)=>{o.startTime=Date.now(),I("info","Incoming Request",{method:o.method,url:r.toString(),headers:{"user-agent":o.headers.get("user-agent"),"content-type":o.headers.get("Content-Type")}})}),n.addHooks("onSend",(o)=>{let r=`${Date.now()-o.req.startTime}ms`;I("info","Response Sent",{method:o.req.method,url:o.url,status:o.status,duration:r,headers:{"content-type":o.headers.get("Content-Type")}})})},O=(n,o,r,g=0,m)=>{let $=s.method[o]||s.reset,i=g>=500?s.error:g>=400?s.warn:s.info,u=n==="<--"?`${n} ${$}${o}${s.reset} ${r}`:`${n} ${$}${o}${s.reset} ${r} ${i}${g}${s.reset} ${m||""}`;console.log(u)},Ln=(n)=>{let o=Date.now()-n;return o<1000?`${o}ms`:`${Math.round(o/1000)}s`},_=(n)=>{n.addHooks("onRequest",(o,r)=>{o.startTime=Date.now(),O("<--",o.method,new URL(r).pathname)}),n.addHooks("onSend",async(o)=>{let{method:r,url:g}=o.req,m=new URL(g).pathname;O("-->",r,m,o.status,Ln(o.req.startTime))}),n.addHooks("routeNotFound",(o)=>{O("[routeNotFound]",o.req.method,o.url.pathname,404)}),n.addHooks("onError",(o,r,g)=>{O(o?.message,r.method,g.toString(),500)})};class H{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;constructor({jwtSecret:n,baseApiUrl:o,enableFileRouting:r,idleTimeOut:g}={}){this.idleTimeOut=g??10,this.enableFileRouter=r??!1,this.baseApiUrl=o||"",this.user_jwt_secret=n||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new T,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[],routeNotFound:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...n)=>{return this.FilterRoutes=n,this.setupFilter()},permitAll:()=>{for(let n of this?.FilterRoutes)this.filters.add(n);return this.FilterRoutes=null,this.setupFilter()},authenticate:(n)=>{if(n?.length)for(let o of n)this.filterFunction.push(o)},authenticateJwt:(n)=>{this.filterFunction.push(Y(n,this.user_jwt_secret))},authenticateJwtDB:(n,o)=>{this.filterFunction.push(Z(n,o,this.user_jwt_secret))}}}redirect(n,o,r){return this.any(n,(g)=>{let m=g.params,$=o;if(m)for(let u in m)$=$.replace(`:${u}`,m[u]);let i=g.url.search;if(i)$+=i;return g.redirect($,r)}),this}serveStatic(n){return this.staticPath=n,this}static(n){return this.staticFiles={...this.staticFiles,...n},this}addHooks(n,o){if(typeof n!=="string")throw new Error("hookName must be a string");if(typeof o!=="function")throw new Error("callback must be a instance of function");switch(n){case"onRequest":this.hooks.onRequest?.push(o);break;case"preHandler":this.hooks.preHandler?.push(o);break;case"postHandler":this.hooks.postHandler?.push(o);break;case"onSend":this.hooks.onSend?.push(o);break;case"onError":this.hooks.onError?.push(o);break;case"onClose":this.hooks.onClose?.push(o);break;case"routeNotFound":this.hooks.routeNotFound?.push(o);break;default:throw new Error(`Unknown hook type: ${n}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[n,o]of this.middlewares.entries())if(o.length>0){this.hasMiddleware=!0;break}if(this.enableFileRouter){let n=process.cwd(),o=N.join(n,"src","routes");if(K?.existsSync(o))this.loadRoutes(o,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(n,o,r){let g=await import(n),m;if(r===".ts")m=N.basename(n,".ts");else if(r===".js")m=N.basename(n,".js");let $=o+"/"+m;if($.endsWith("/index"))$=o;else if($.endsWith("/api"))$=o;$=$.replace(/\[(.*?)\]/g,":$1");let i=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let u of i)if(g[u]){let f=u.toLowerCase(),v=g[u];this[f](`${this.baseApiUrl}${$}`,v)}}async loadRoutes(n,o){let r=await K.promises.readdir(n);for(let g of r){let m=N.join(n,g);if((await K.promises.stat(m)).isDirectory())this.loadRoutes(m,o+"/"+g);else if(g.endsWith(".ts"))this.registerFileRoutes(m,o,".ts");else if(g.endsWith(".js"))this.registerFileRoutes(m,o,".js")}}useLogger(n){return _(n),this}useAdvancedLogger(n){return Q(n),this}listen(n,...o){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let r="0.0.0.0",g=void 0,m={};for(let i of o)if(typeof i==="string")r=i;else if(typeof i==="function")g=i;else if(typeof i==="object"&&i!==null)m=i;this.compile();let $={port:n,hostname:r,idleTimeOut:this.idleTimeOut,fetch:async(i,u)=>{let f=new URL(i.url);if(this.hooks.onRequest){let v=this.hooks.onRequest;for(let A=0;A<v.length;A++)await v[A](i,f,u)}return G(i,u,f,this)},static:this.staticFiles};if(m.sslCert&&m.sslKey)$.certFile=m.sslCert,$.keyFile=m.sslKey;if(this.serverInstance=Bun?.serve($),m.sslCert&&m.sslKey)console.log(`HTTPS server is running on https://localhost:${n}`);if(g)return g();return this.serverInstance}close(n){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,n?n():console.log("Server has been stopped");else console.warn("Server is not running.")}route(n,o){if(!n||typeof n!=="string")throw new Error("Path must be a string");let r=Object.fromEntries(o.tempRoutes);return Object.entries(r).forEach(([m,$])=>{let i=m.replace(/::\w+$/,""),u=`${n}${i}`;if(!this.middlewares.has(u))this.middlewares.set(u,[]);$.handlers.slice(0,-1).forEach((C)=>{if(!this.middlewares.get(u)?.includes(C))this.middlewares.get(u)?.push(C)});let v=$.handlers[$.handlers.length-1],A=$.method;try{this.trie.insert(u,{handler:v,method:A})}catch(C){console.error(`Error inserting ${u}:`,C)}}),o=null,this}register(n,o){return this.route(n,o)}addRoute(n,o,r){if(typeof o!=="string")throw new Error(`Error in ${r[r.length-1]}: Path must be a string. Received: ${typeof o}`);if(typeof n!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof n}`);this.tempRoutes?.set(o+"::"+n,{method:n,handlers:r});let g=r.slice(0,-1),m=r[r.length-1];if(!this.middlewares.has(o))this.middlewares.set(o,[]);g.forEach(($)=>{if(o==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...g])];else if(!this.middlewares.get(o)?.includes($))this.middlewares.get(o)?.push($)});try{if(n==="ANY"){let $=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let i of $)this.trie.insert(o,{handler:m,method:i})}this.trie.insert(o,{handler:m,method:n})}catch($){console.error(`Error inserting ${o}:`,$)}}use(n,o){if(Array.isArray(n))n.forEach((g)=>{if(typeof g==="function")this.globalMiddlewares.push(g)});if(typeof n==="function"){if(this.globalMiddlewares.push(n),Array.isArray(o))o.forEach((g)=>{this.globalMiddlewares.push(g)});return}return(Array.isArray(n)?n.filter((g)=>typeof g==="string"):[n].filter((g)=>typeof g==="string")).forEach((g)=>{if(!this.middlewares.has(g))this.middlewares.set(g,[]);if(o)(Array.isArray(o)?o:[o]).forEach(($)=>{this.middlewares.get(g)?.push($)})}),this}get(n,...o){return this.addRoute("GET",n,o),this}post(n,...o){return this.addRoute("POST",n,o),this}put(n,...o){return this.addRoute("PUT",n,o),this}patch(n,...o){return this.addRoute("PATCH",n,o),this}delete(n,...o){return this.addRoute("DELETE",n,o),this}any(n,...o){return this.addRoute("ANY",n,o),this}head(n,...o){return this.addRoute("HEAD",n,o),this}options(n,...o){return this.addRoute("OPTIONS",n,o),this}propfind(n,...o){return this.addRoute("PROPFIND",n,o),this}}export{H as default};
@@ -1,3 +1,3 @@
1
- var r={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},d=(o,e,t)=>{let n=r[o]||r.reset,s=t?.method?r.method[t.method]||r.reset:r.reset;console.log(`
2
- ${n}[${o.toUpperCase()}]${r.reset} ${e} - ${s}${t?.method||""}${r.reset}`),console.log(JSON.stringify({timestamp:new Date().toISOString(),...t},null,2)+`
3
- `)},i=(o)=>{o.addHooks("onRequest",async(e,t)=>{e.startTime=Date.now(),d("info","Incoming Request",{method:e.method,url:t.toString(),headers:{"user-agent":e.headers.get("user-agent"),"content-type":e.headers.get("Content-Type")}})}),o.addHooks("postHandler",(e)=>{let t=`${Date.now()-e.req.startTime}ms`;d("info","Response Sent",{method:e.req.method,url:e.url,status:e.status,duration:t,headers:{"content-type":e.headers.get("Content-Type")}})})},a=(o,e,t,n=0,s)=>{let m=o==="<--"?`${o} ${e} ${t}`:`${o} ${e} ${t} ${n} ${s||""}`;console.log(m)},g=(o)=>{let e=Date.now()-o;return e<1000?`${e}ms`:`${Math.round(e/1000)}s`},u=(o)=>{o.addHooks("onRequest",(e,t)=>{e.startTime=Date.now(),a("<--",e.method,new URL(t).pathname)}),o.addHooks("postHandler",async(e)=>{let{method:t,url:n}=e.req,s=new URL(n).pathname;a("-->",t,s,e.status,g(e.req.startTime))}),o.addHooks("routeNotFound",(e)=>{a("routeNotFound",e.req.method,e.url.pathname,404)}),o.addHooks("onError",(e,t,n)=>{d("error","Error occurred",{method:t.method,url:n.toString()})})};export{u as logger,i as advancedLogger};
1
+ var o={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},m=(n,e,t)=>{let s=o[n]||o.reset,r=t?.method?o.method[t.method]||o.reset:o.reset,d=t?.status?t.status>=500?o.error:t.status>=400?o.warn:o.info:o.reset;console.log(`
2
+ ${s}[${n.toUpperCase()}]${o.reset} ${e} - ${r}${t?.method||""}${o.reset}`);let g={timestamp:new Date().toISOString(),...t,status:t?.status?`${d}${t.status}${o.reset}`:void 0,method:t?.method?`${r}${t.method}${o.reset}`:void 0};console.log(JSON.stringify(g,null,2)+`
3
+ `)},h=(n)=>{n.addHooks("onRequest",async(e,t)=>{e.startTime=Date.now(),m("info","Incoming Request",{method:e.method,url:t.toString(),headers:{"user-agent":e.headers.get("user-agent"),"content-type":e.headers.get("Content-Type")}})}),n.addHooks("onSend",(e)=>{let t=`${Date.now()-e.req.startTime}ms`;m("info","Response Sent",{method:e.req.method,url:e.url,status:e.status,duration:t,headers:{"content-type":e.headers.get("Content-Type")}})})},a=(n,e,t,s=0,r)=>{let d=o.method[e]||o.reset,g=s>=500?o.error:s>=400?o.warn:o.info,i=n==="<--"?`${n} ${d}${e}${o.reset} ${t}`:`${n} ${d}${e}${o.reset} ${t} ${g}${s}${o.reset} ${r||""}`;console.log(i)},u=(n)=>{let e=Date.now()-n;return e<1000?`${e}ms`:`${Math.round(e/1000)}s`},$=(n)=>{n.addHooks("onRequest",(e,t)=>{e.startTime=Date.now(),a("<--",e.method,new URL(t).pathname)}),n.addHooks("onSend",async(e)=>{let{method:t,url:s}=e.req,r=new URL(s).pathname;a("-->",t,r,e.status,u(e.req.startTime))}),n.addHooks("routeNotFound",(e)=>{a("[routeNotFound]",e.req.method,e.url.pathname,404)}),n.addHooks("onError",(e,t,s)=>{a(e?.message,t.method,s.toString(),500)})};export{$ as logger,h as advancedLogger};
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @module
3
+ * Powered By Middleware for Diesel.
4
+ */
5
+ import { middlewareFunc } from "../../types";
6
+ type PoweredByOptions = {
7
+ /**
8
+ * The value for X-Powered-By header.
9
+ * @default Diesel
10
+ */
11
+ serverName?: string;
12
+ };
13
+ /**
14
+ * Powered By Middleware for Diesel.
15
+ *
16
+ * @param options - The options for the Powered By Middleware.
17
+ * @returns {MiddlewareHandler} The middleware handler function.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { poweredBy } from 'diesel-core/powered-by'
22
+ *
23
+ * const app = new Diesel()
24
+ *
25
+ * app.use(poweredBy()) // With options: poweredBy({ serverName: "My Server" })
26
+ * ```
27
+ */
28
+ export declare const poweredBy: (options?: PoweredByOptions) => middlewareFunc;
29
+ export {};
package/dist/types.d.ts CHANGED
@@ -42,6 +42,8 @@ export interface ContextType {
42
42
  cookies: any;
43
43
  removeHeader: (key: string) => this;
44
44
  ejs: (viewPath: string, data: {}) => Response | Promise<Response>;
45
+ stream: (callback: () => void) => Response;
46
+ yieldStream: (callback: () => AsyncIterable<any>) => Response;
45
47
  }
46
48
  export interface CookieOptions {
47
49
  maxAge?: number;
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- var H=Object.create;var{getPrototypeOf:I,defineProperty:G,getOwnPropertyNames:K}=Object;var L=Object.prototype.hasOwnProperty;var N=(q,C,z)=>{z=q!=null?H(I(q)):{};let v=C||!q||!q.__esModule?G(z,"default",{value:q,enumerable:!0}):z;for(let A of K(q))if(!L.call(v,A))G(v,A,{get:()=>q[A],enumerable:!0});return v};var O=((q)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(q,{get:(C,z)=>(typeof require!=="undefined"?require:C)[z]}):q)(function(q){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+q+'" is not supported')});function R(q){switch(q.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function S(q,C){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let v=z.cookies?.accessToken||z.req?.headers?.get("Authorization");if(!v)return z.json({message:"Unauthorized: No token provided"},401);if(v.startsWith("Bearer "))v=v.slice(7);let A=q?.verify(v,C);if(!A)return z.json({message:"Unauthorized: Invalid token"},401);z.set("user",A);return}catch(v){return z.json({message:"Unauthorized: Invalid token",error:v?.message},401)}}}function V(q,C,z){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!C)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(v)=>{try{let A=v.cookies?.accessToken||v.req?.headers?.get("Authorization");if(!A)return v.json({message:"Unauthorized: No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let E=q?.verify(A,z);if(!E)return v.json({message:"Unauthorized: Invalid token"},401);let F=await C.findById(E._id).select("-password -refreshToken");if(!F)return v.json({message:"Unauthorized: User not found"},401);v.set("user",F);return}catch(A){return v.json({message:"Unauthorized: Authentication failed",error:A?.message},401)}}}export{R as getMimeType,S as authenticateJwtMiddleware,V as authenticateJwtDbMiddleware};
1
+ var H=Object.create;var{getPrototypeOf:I,defineProperty:G,getOwnPropertyNames:K}=Object;var L=Object.prototype.hasOwnProperty;var N=(q,C,z)=>{z=q!=null?H(I(q)):{};let v=C||!q||!q.__esModule?G(z,"default",{value:q,enumerable:!0}):z;for(let A of K(q))if(!L.call(v,A))G(v,A,{get:()=>q[A],enumerable:!0});return v};var O=((q)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(q,{get:(C,z)=>(typeof require!=="undefined"?require:C)[z]}):q)(function(q){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+q+'" is not supported')});function R(q){switch(q.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function S(q,C){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let v=z.cookies?.accessToken||z.req?.headers?.get("Authorization");if(!v)return z.json({message:"Unauthorized: No token provided"},401);if(v.startsWith("Bearer "))v=v.slice(7);let A=q?.verify(v,C);if(!A)return z.json({message:"Unauthorized: Invalid token"},401);z.set("user",A)}catch(v){return console.error("JWT verification error:",v),z.json({message:"Unauthorized: Invalid token",error:v?.message},401)}}}function V(q,C,z){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!C)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(v)=>{try{let A=v.cookies?.accessToken||v.req?.headers?.get("Authorization");if(!A)return v.json({message:"Unauthorized: No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let E=q?.verify(A,z);if(!E)return v.json({message:"Unauthorized: Invalid token"},401);let F=await C.findById(E._id).select("-password -refreshToken");if(!F)return v.json({message:"Unauthorized: User not found"},401);v.set("user",F);return}catch(A){return v.json({message:"Unauthorized: Authentication failed",error:A?.message},401)}}}export{R as getMimeType,S as authenticateJwtMiddleware,V as authenticateJwtDbMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "1.1.7",
3
+ "version": "1.1.8",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",