diesel-core 0.0.15 → 0.0.16

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/types.d.ts CHANGED
@@ -42,8 +42,8 @@ export interface ContextType {
42
42
  redirect: (path: string, status?: number) => Response;
43
43
  getParams: (props?: any) => any;
44
44
  getQuery: (props?: any) => any;
45
- cookie: (name: string, value: string, options?: CookieOptions) => Promise<this>;
46
- getCookie: (cookieName?: string) => Promise<any>;
45
+ cookie: (name: string, value: string, options?: CookieOptions) => this;
46
+ getCookie: (cookieName?: string) => any;
47
47
  }
48
48
  export interface CookieOptions {
49
49
  maxAge?: number;
package/example/main.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Server } from "bun";
2
2
  import Diesel ,{rateLimit} from "../src/main";
3
- import { ContextType, CookieOptions, middlewareFunc } from "../dist/types";
4
3
  import jwt from 'jsonwebtoken'
4
+ import { ContextType, CookieOptions, middlewareFunc } from "../src/types";
5
5
 
6
6
  const app = new Diesel()
7
7
  const secret = 'pradeep'
@@ -12,15 +12,17 @@ const secret = 'pradeep'
12
12
  // })
13
13
 
14
14
  async function authJwt (ctx:ContextType, server?:Server): Promise<void | Response> {
15
- const token = await ctx.getCookie("accessToken"); // Retrieve the JWT token from cookies
15
+
16
+ const token = ctx?.getCookie("accessToken");
16
17
  if (!token) {
17
18
  return ctx.status(401).json({ message: "Authentication token missing" });
18
19
  }
19
20
  try {
21
+
20
22
  // Verify the JWT token using a secret key
21
23
  const user = jwt.verify(token, secret); // Replace with your JWT secret
22
24
  // Set the user data in context
23
- ctx.setUser(user);
25
+ ctx.set('user',user);
24
26
 
25
27
  // Proceed to the next middleware/route handler
26
28
  return ctx.next();
@@ -37,11 +39,11 @@ const limiter = rateLimit({
37
39
  // app.use(h)
38
40
  // app.use(limiter)
39
41
 
40
- // app
41
- // .filter()
42
- // .routeMatcher('/api/user/register','/api/user/login','/test/:id','/cookie')
43
- // .permitAll()
44
- // .require(authJwt as middlewareFunc)
42
+ app
43
+ .filter()
44
+ .routeMatcher('/api/user/register','/api/user/login','/test/:id','/cookie')
45
+ .permitAll()
46
+ .require(authJwt as middlewareFunc)
45
47
 
46
48
  // app.use(authJwt)
47
49
 
@@ -49,10 +51,11 @@ const limiter = rateLimit({
49
51
 
50
52
  app.get("/", async(xl) => {
51
53
  // // const ip = xl.req
52
- // // console.log(ip)
53
- // const user = xl.getUser()
54
- // return xl.json({user:user});
55
- return xl.status(200).text("hello world")
54
+ // // // console.log(ip)
55
+ // const user = xl.get('user')
56
+ const q = xl.get('user');
57
+ console.log(q)
58
+ return xl.status(200).json({msg:"hello world",q})
56
59
  });
57
60
 
58
61
  app.get("/test/:id", async (xl) => {
@@ -80,11 +83,10 @@ app.get("/test/:id", async (xl) => {
80
83
  sameSite: "Strict", // Prevents CSRF (strict origin policy)
81
84
  path: "/", // Cookie available for all routes
82
85
  };
83
- await xl.cookie("accessToken", accessToken, options)
84
- await xl.cookie("refreshToken", refreshToken, options)
85
- // xl.cookie("refreshToken", refreshToken, options);
86
- await xl.getCookie()
87
- return xl.json({msg:"setting cookies"})
86
+ return xl
87
+ .cookie("accessToken", accessToken, options)
88
+ .cookie("refreshToken", refreshToken, options)
89
+ .json({msg:"setting cookies"})
88
90
  });
89
91
 
90
92
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "0.0.15",
4
- "main": "dist/main.js",
3
+ "version": "0.0.16",
4
+ "main": "src/main.ts",
5
5
  "types": "dist/main.d.ts",
6
6
  "scripts": {
7
7
  "build": "bun run build.js"
package/src/ctx.ts CHANGED
@@ -111,22 +111,22 @@ export default function createCtx(req: Request, server:Server ,url: URL): Contex
111
111
  },
112
112
 
113
113
  getParams(props: string)
114
- : string | Record<string, string> | null {
114
+ : string | Record<string, string> | {} {
115
115
  if (!parsedParams) {
116
116
  parsedParams = extractDynamicParams(req?.routePattern, url?.pathname);
117
117
  }
118
- return props ? parsedParams[props] || null : parsedParams;
118
+ return props ? parsedParams[props] || {} : parsedParams;
119
119
  },
120
120
 
121
121
  getQuery(props?: any)
122
- : string | Record<string, string> | null {
122
+ : string | Record<string, string> | {} {
123
123
  if (!parsedQuery) {
124
124
  parsedQuery = Object.fromEntries(url.searchParams);
125
125
  }
126
- return props ? parsedQuery[props] || null : parsedQuery;
126
+ return props ? parsedQuery[props] || {} : parsedQuery;
127
127
  },
128
128
 
129
- async cookie(name: string, value: string, options: CookieOptions = {}): Promise<ContextType> {
129
+ cookie(name: string, value: string, options: CookieOptions = {}) {
130
130
  let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
131
131
 
132
132
  // Add options to cookie string (e.g., expiration, path, HttpOnly, etc.)
@@ -143,22 +143,24 @@ export default function createCtx(req: Request, server:Server ,url: URL): Contex
143
143
  return this;
144
144
  },
145
145
 
146
- async getCookie(cookieName?: string)
147
- : Promise<string | Record<string, string> | null> {
146
+ getCookie(cookieName?: string){
148
147
  if (!parsedCookie) {
149
148
  const cookieHeader = req.headers?.get("cookie")
150
149
  if (cookieHeader) {
151
- parsedCookie = await parseCookie(cookieHeader);
150
+ parsedCookie = parseCookie(cookieHeader);
152
151
  }
153
152
  }
154
- return cookieName ? parsedCookie[cookieName] || null : parsedCookie;
153
+ if (!parsedCookie) {
154
+ return null
155
+ }
156
+ return cookieName ? (parsedCookie[cookieName] !== undefined ? parsedCookie[cookieName] : null) : parsedCookie;
155
157
  },
156
158
  };
157
159
  }
158
160
 
159
161
 
160
- async function parseCookie(header: string | undefined)
161
- : Promise<Record<string, string>> {
162
+ function parseCookie(header: string | undefined)
163
+ : Record<string, string> {
162
164
  const cookies: Record<string, string> = {};
163
165
  if (!header) return cookies;
164
166
 
package/src/types.ts CHANGED
@@ -47,8 +47,8 @@ export interface ContextType {
47
47
  redirect: (path: string, status?: number) => Response;
48
48
  getParams: (props?: any) => any;
49
49
  getQuery: (props?: any) => any;
50
- cookie: (name: string, value: string, options?: CookieOptions) => Promise<this>;
51
- getCookie: (cookieName?: string) => Promise<any>;
50
+ cookie: (name: string, value: string, options?: CookieOptions) => this;
51
+ getCookie: (cookieName?: string) => any;
52
52
  }
53
53
 
54
54
  export interface CookieOptions {
package/dist/ctx.js DELETED
@@ -1 +0,0 @@
1
- function $(E,F,I){let G=new Headers,R={},L=!1,U=null,X=null,Y=null,Z,_=200;return{req:E,server:F,url:I,next:()=>{},status(w){return _=w,this},getIP(){return this.server.requestIP(this.req)},async body(){if(!Z)Z=await O(E);if(Z.error)return new Response(JSON.stringify({error:Z.error}),{status:400});return Z},setHeader(w,z){return G.set(w,z),this},set(w,z){return R[w]=z,this},get(w){return R[w]||null},setAuth(w){return L=w,this},getAuth(){return L},text(w,z){return new Response(w,{status:z??_,headers:G})},json(w,z){return new Response(JSON.stringify(w),{status:z??_,headers:G})},html(w,z){return new Response(Bun.file(w),{status:z??_,headers:G})},file(w,z){return new Response(Bun.file(w),{status:z??_,headers:G})},redirect(w,z){return G.set("Location",w),new Response(null,{status:z??302,headers:G})},getParams(w){if(!Y)Y=W(E?.routePattern,I?.pathname);return w?Y[w]||null:Y},getQuery(w){if(!U)U=Object.fromEntries(I.searchParams);return w?U[w]||null:U},async cookie(w,z,J={}){let M=`${encodeURIComponent(w)}=${encodeURIComponent(z)}`;if(J.maxAge)M+=`; Max-Age=${J.maxAge}`;if(J.expires)M+=`; Expires=${J.expires.toUTCString()}`;if(J.path)M+=`; Path=${J.path}`;if(J.domain)M+=`; Domain=${J.domain}`;if(J.secure)M+="; Secure";if(J.httpOnly)M+="; HttpOnly";if(J.sameSite)M+=`; SameSite=${J.sameSite}`;return G?.append("Set-Cookie",M),this},async getCookie(w){if(!X){let z=E.headers.get("cookie");if(z)X=await K(z)}return w?X[w]||null:X}}}async function K(E){let F={};if(!E)return F;return E.split(";").forEach((G)=>{let[R,L]=G?.trim()?.split("=");if(R&&L)F[R.trim()]=L.split(" ")[0].trim()}),F}function W(E,F){let I={},G=E.split("/"),[R]=F.split("?"),L=R.split("/");if(G.length!==L.length)return null;return G.forEach((U,X)=>{if(U.startsWith(":")){let Y=U.slice(1);I[Y]=L[X]}}),I}async function O(E){let F=E.headers.get("Content-Type")||"";if(!F)return{};try{if(F.startsWith("application/json"))return await E.json();if(F.startsWith("application/x-www-form-urlencoded")){let I=await E.text();return Object.fromEntries(new URLSearchParams(I))}if(F.startsWith("multipart/form-data")){let I=await E.formData();return A(I)}return{error:"Unknown request body type"}}catch(I){return{error:"Invalid request body format"}}}function A(E){let F={};for(let[I,G]of E.entries())F[I]=G;return F}export{$ as default};
@@ -1 +0,0 @@
1
- function W(G,E,I){let z=new Headers,J={},U=!1,Z=null,L=null,Y=null,$,M=200;return{req:G,server:E,url:I,next:()=>{},status(F){return M=F,this},getIP(){return this.server.requestIP(this.req)},async body(){if(!$)$=await j(G);if($.error)return new Response(JSON.stringify({error:$.error}),{status:400});return $},setHeader(F,X){return z.set(F,X),this},set(F,X){return J[F]=X,this},get(F){return J[F]||null},setAuth(F){return U=F,this},getAuth(){return U},text(F,X){return new Response(F,{status:X??M,headers:z})},json(F,X){return new Response(JSON.stringify(F),{status:X??M,headers:z})},html(F,X){return new Response(Bun.file(F),{status:X??M,headers:z})},file(F,X){return new Response(Bun.file(F),{status:X??M,headers:z})},redirect(F,X){return z.set("Location",F),new Response(null,{status:X??302,headers:z})},getParams(F){if(!Y)Y=V(G?.routePattern,I?.pathname);return F?Y[F]||null:Y},getQuery(F){if(!Z)Z=Object.fromEntries(I.searchParams);return F?Z[F]||null:Z},async cookie(F,X,_={}){let K=`${encodeURIComponent(F)}=${encodeURIComponent(X)}`;if(_.maxAge)K+=`; Max-Age=${_.maxAge}`;if(_.expires)K+=`; Expires=${_.expires.toUTCString()}`;if(_.path)K+=`; Path=${_.path}`;if(_.domain)K+=`; Domain=${_.domain}`;if(_.secure)K+="; Secure";if(_.httpOnly)K+="; HttpOnly";if(_.sameSite)K+=`; SameSite=${_.sameSite}`;return z?.append("Set-Cookie",K),this},async getCookie(F){if(!L){let X=G.headers.get("cookie");if(X)L=await A(X)}return F?L[F]||null:L}}}async function A(G){let E={};if(!G)return E;return G.split(";").forEach((z)=>{let[J,U]=z?.trim()?.split("=");if(J&&U)E[J.trim()]=U.split(" ")[0].trim()}),E}function V(G,E){let I={},z=G.split("/"),[J]=E.split("?"),U=J.split("/");if(z.length!==U.length)return null;return z.forEach((Z,L)=>{if(Z.startsWith(":")){let Y=Z.slice(1);I[Y]=U[L]}}),I}async function j(G){let E=G.headers.get("Content-Type")||"";if(!E)return{};try{if(E.startsWith("application/json"))return await G.json();if(E.startsWith("application/x-www-form-urlencoded")){let I=await G.text();return Object.fromEntries(new URLSearchParams(I))}if(E.startsWith("multipart/form-data")){let I=await G.formData();return D(I)}return{error:"Unknown request body type"}}catch(I){return{error:"Invalid request body format"}}}function D(G){let E={};for(let[I,z]of G.entries())E[I]=z;return E}async function Q(G,E,I,z){let J=W(G,E,I),U=z.trie.search(I.pathname,G.method);if(!U||U.method!==G.method)return new Response(U?"Method not allowed":`Route not found for ${I.pathname}`,{status:U?405:404});if(U.isDynamic)G.routePattern=U.path;if(z.corsConfig){let L=await T(G,J,z.corsConfig);if(L)return L}if(z.hasOnReqHook&&z.hooks.onRequest)z.hooks.onRequest(J,E);if(z.filters.length>0){let L=G.routePattern??I.pathname;if(z.filters.includes(L)===!1)if(z.filterFunction){let $=await z?.filterFunction(J,E);if($)return $}else return new Response(JSON.stringify({message:"Authentication required"}),{status:400})}if(z.hasMiddleware){let L=[...z.globalMiddlewares,...z.middlewares.get(I.pathname)||[]];for(let Y of L){let $=await Y(J,E);if($)return $}}if(z.hasPreHandlerHook&&z.hooks.preHandler){let L=await z.hooks.preHandler(J);if(L)return L}let Z=z.hasPreHandlerHook?await z.hooks.preHandler?.(J):null;if(Z)return Z;try{let L=await U.handler(J);if(z.hasPostHandlerHook&&z.hooks.postHandler)await z.hooks.postHandler(J);if(z.hasOnSendHook&&z.hooks.onSend){let Y=await z.hooks.onSend(J,L);if(Y)return Y}return L??new Response("No response from handler",{status:204})}catch(L){return new Response("Internal Server Error",{status:500})}}async function T(G,E,I={}){let z=G.headers.get("origin")??"*",J=I?.origin,U=I?.allowedHeaders??["Content-Type","Authorization"],Z=I?.methods??["GET","POST","PUT","DELETE","OPTIONS"],L=I?.credentials??!1,Y=I?.exposedHeaders??[];if(E.setHeader("Access-Control-Allow-Methods",Z),E.setHeader("Access-Control-Allow-Headers",U),E.setHeader("Access-Control-Allow-Credentials",L),Y.length)E.setHeader("Access-Control-Expose-Headers",Y);if(J==="*")E.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(J))if(z&&J.includes(z))E.setHeader("Access-Control-Allow-Origin",z);else if(J.includes("*"))E.setHeader("Access-Control-Allow-Origin","*");else return E.status(403).json({message:"CORS not allowed"});else if(typeof J==="string")if(z===J)E.setHeader("Access-Control-Allow-Origin",z);else return E.status(403).json({message:"CORS not allowed"});else return E.status(403).json({message:"CORS not allowed"});if(E.setHeader("Access-Control-Allow-Origin",z),G.method==="OPTIONS")return E.setHeader("Access-Control-Max-Age","86400"),E.status(204).text("");return null}export{Q as default};
package/dist/main.js DELETED
@@ -1 +0,0 @@
1
- class D{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class Q{root;constructor(){this.root=new D}insert(z,F){let G=this.root,J=z.split("/").filter(Boolean);if(z==="/"){G.isEndOfWord=!0,G.handler.push(F.handler),G.path=z,G.method.push(F.method);return}for(let U of J){let X=!1,_=U;if(U.startsWith(":"))X=!0,_=":";if(!G.children[_])G.children[_]=new D;G=G.children[_],G.isDynamic=X,G.pattern=U}G.isEndOfWord=!0,G.method.push(F.method),G.handler.push(F.handler),G.path=z}search(z,F){let G=this.root,J=z.split("/").filter(Boolean);for(let X of J){let _=X;if(!G.children[_])if(G.children[":"])G=G.children[":"];else return null;else G=G.children[_]}let U=G.method.indexOf(F);if(U!==-1)return{path:G.path,handler:G.handler[U],isDynamic:G.isDynamic,pattern:G.pattern,method:G.method[U]};return{path:G.path,handler:G.handler,isDynamic:G.isDynamic,pattern:G.pattern,method:G.method[U]}}}function K(z,F,G){let J=new Headers,U={},X=!1,_=null,Y=null,$=null,L,V=200;return{req:z,server:F,url:G,next:()=>{},status(Z){return V=Z,this},getIP(){return this.server.requestIP(this.req)},async body(){if(!L)L=await b(z);if(L.error)return new Response(JSON.stringify({error:L.error}),{status:400});return L},setHeader(Z,E){return J.set(Z,E),this},set(Z,E){return U[Z]=E,this},get(Z){return U[Z]||null},setAuth(Z){return X=Z,this},getAuth(){return X},text(Z,E){return new Response(Z,{status:E??V,headers:J})},json(Z,E){return new Response(JSON.stringify(Z),{status:E??V,headers:J})},html(Z,E){return new Response(Bun.file(Z),{status:E??V,headers:J})},file(Z,E){return new Response(Bun.file(Z),{status:E??V,headers:J})},redirect(Z,E){return J.set("Location",Z),new Response(null,{status:E??302,headers:J})},getParams(Z){if(!$)$=T(z?.routePattern,G?.pathname);return Z?$[Z]||null:$},getQuery(Z){if(!_)_=Object.fromEntries(G.searchParams);return Z?_[Z]||null:_},async cookie(Z,E,W={}){let A=`${encodeURIComponent(Z)}=${encodeURIComponent(E)}`;if(W.maxAge)A+=`; Max-Age=${W.maxAge}`;if(W.expires)A+=`; Expires=${W.expires.toUTCString()}`;if(W.path)A+=`; Path=${W.path}`;if(W.domain)A+=`; Domain=${W.domain}`;if(W.secure)A+="; Secure";if(W.httpOnly)A+="; HttpOnly";if(W.sameSite)A+=`; SameSite=${W.sameSite}`;return J?.append("Set-Cookie",A),this},async getCookie(Z){if(!Y){let E=z.headers.get("cookie");if(E)Y=await N(E)}return Z?Y[Z]||null:Y}}}async function N(z){let F={};if(!z)return F;return z.split(";").forEach((J)=>{let[U,X]=J?.trim()?.split("=");if(U&&X)F[U.trim()]=X.split(" ")[0].trim()}),F}function T(z,F){let G={},J=z.split("/"),[U]=F.split("?"),X=U.split("/");if(J.length!==X.length)return null;return J.forEach((_,Y)=>{if(_.startsWith(":")){let $=_.slice(1);G[$]=X[Y]}}),G}async function b(z){let F=z.headers.get("Content-Type")||"";if(!F)return{};try{if(F.startsWith("application/json"))return await z.json();if(F.startsWith("application/x-www-form-urlencoded")){let G=await z.text();return Object.fromEntries(new URLSearchParams(G))}if(F.startsWith("multipart/form-data")){let G=await z.formData();return C(G)}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}function C(z){let F={};for(let[G,J]of z.entries())F[G]=J;return F}async function M(z,F,G,J){let U=K(z,F,G),X=J.trie.search(G.pathname,z.method);if(!X||X.method!==z.method)return new Response(X?"Method not allowed":`Route not found for ${G.pathname}`,{status:X?405:404});if(X.isDynamic)z.routePattern=X.path;if(J.corsConfig){let Y=await v(z,U,J.corsConfig);if(Y)return Y}if(J.hasOnReqHook&&J.hooks.onRequest)J.hooks.onRequest(U,F);if(J.filters.length>0){let Y=z.routePattern??G.pathname;if(J.filters.includes(Y)===!1)if(J.filterFunction){let L=await J?.filterFunction(U,F);if(L)return L}else return new Response(JSON.stringify({message:"Authentication required"}),{status:400})}if(J.hasMiddleware){let Y=[...J.globalMiddlewares,...J.middlewares.get(G.pathname)||[]];for(let $ of Y){let L=await $(U,F);if(L)return L}}if(J.hasPreHandlerHook&&J.hooks.preHandler){let Y=await J.hooks.preHandler(U);if(Y)return Y}let _=J.hasPreHandlerHook?await J.hooks.preHandler?.(U):null;if(_)return _;try{let Y=await X.handler(U);if(J.hasPostHandlerHook&&J.hooks.postHandler)await J.hooks.postHandler(U);if(J.hasOnSendHook&&J.hooks.onSend){let $=await J.hooks.onSend(U,Y);if($)return $}return Y??new Response("No response from handler",{status:204})}catch(Y){return new Response("Internal Server Error",{status:500})}}async function v(z,F,G={}){let J=z.headers.get("origin")??"*",U=G?.origin,X=G?.allowedHeaders??["Content-Type","Authorization"],_=G?.methods??["GET","POST","PUT","DELETE","OPTIONS"],Y=G?.credentials??!1,$=G?.exposedHeaders??[];if(F.setHeader("Access-Control-Allow-Methods",_),F.setHeader("Access-Control-Allow-Headers",X),F.setHeader("Access-Control-Allow-Credentials",Y),$.length)F.setHeader("Access-Control-Expose-Headers",$);if(U==="*")F.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(U))if(J&&U.includes(J))F.setHeader("Access-Control-Allow-Origin",J);else if(U.includes("*"))F.setHeader("Access-Control-Allow-Origin","*");else return F.status(403).json({message:"CORS not allowed"});else if(typeof U==="string")if(J===U)F.setHeader("Access-Control-Allow-Origin",J);else return F.status(403).json({message:"CORS not allowed"});else return F.status(403).json({message:"CORS not allowed"});if(F.setHeader("Access-Control-Allow-Origin",J),z.method==="OPTIONS")return F.setHeader("Access-Control-Max-Age","86400"),F.status(204).text("");return null}function B(z){let{time:F=60000,max:G=100,message:J="Rate limit exceeded. Please try again later."}=z,U=new Map;return(X)=>{let _=new Date,Y=X.getIP().address;if(!U.has(Y))U.set(Y,{count:0,startTime:_});let $=U.get(Y);if($)if(_-$.startTime>F)$.count=1,$.startTime=_;else $.count++;if($&&$.count>G)return X.status(429).json({error:J});X.next()}}class j{routes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hooks;corsConfig;filters;filterFunction;constructor(){this.routes=[],this.filters=[],this.filterFunction=null,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new Q,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null}}filter(){return{routeMatcher:(...z)=>{return this.routes=z.sort(),this.filter()},permitAll:()=>{for(let z of this?.routes)this.filters.push(z);return this.filter()},require:(z)=>{if(!z||typeof z!=="function")return new Response(JSON.stringify({message:"Authentication required"}),{status:400});this.filterFunction=z}}}cors(z){this.corsConfig=z}addHooks(z,F){if(typeof z!=="string")throw new Error("hookName must be a string");if(typeof F!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(z))this.hooks[z]=F;else throw new Error(`Unknown hook type: ${z}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[z,F]of this.middlewares.entries())if(F.length>0){this.hasMiddleware=!0;break}if(this.hooks.onRequest)this.hasOnReqHook=!0;if(this.hooks.preHandler)this.hasPreHandlerHook=!0;if(this.hooks.postHandler)this.hasPostHandlerHook=!0;if(this.hooks.onSend)this.hasOnSendHook=!0}listen(z,F,{sslCert:G=null,sslKey:J=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof z!=="number")throw new Error("Port must be a numeric value");this.compile();let U=this,X={port:z,fetch:async(Y,$)=>{let L=new URL(Y.url);try{return await M(Y,$,L,this)}catch(V){return new Response("Internal Server Error",{status:500})}},onClose(){console.log("Server is shutting down...")}};if(G&&J)X.certFile=G,X.keyFile=J;let _=Bun.serve(X);if(typeof F==="function")return F();if(G&&J)console.log(`HTTPS server is running on https://localhost:${z}`);else console.log(`HTTP server is running on http://localhost:${z}`);return _}register(z,F){if(typeof z!=="string")throw new Error("path must be a string");if(typeof F!=="object")throw new Error("handler parameter should be a instance of router object",F);let G=Object.entries(F.trie.root.children);F.trie.root.subMiddlewares.forEach((J,U)=>{if(!this.middlewares.has(z+U))this.middlewares.set(z+U,[]);J?.forEach((X)=>{if(!this.middlewares.get(z+U)?.includes(X))this.middlewares.get(z+U)?.push(X)})});for(let[J,U]of G){let X=z+U?.path,_=U.handler[0],Y=U.method[0];this.trie.insert(X,{handler:_,method:Y})}F.trie=new Q}#z(z,F,G){if(typeof F!=="string")throw new Error("Path must be a string type");if(typeof z!=="string")throw new Error("method must be a string type");let J=G.slice(0,-1),U=G[G.length-1];if(!this.middlewares.has(F))this.middlewares.set(F,[]);J.forEach((X)=>{if(F==="/"){if(!this.globalMiddlewares.includes(X))this.globalMiddlewares.push(X)}else if(!this.middlewares.get(F)?.includes(X))this.middlewares.get(F)?.push(X)}),this.trie.insert(F,{handler:U,method:z})}use(z,F){if(typeof z==="function"){if(!this.globalMiddlewares.includes(z))this.globalMiddlewares.push(z);return}let G=z;if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(F){if(!this.middlewares.get(G)?.includes(F))this.middlewares.get(G)?.push(F)}}get(z,...F){return this.#z("GET",z,F),this}post(z,...F){return this.#z("POST",z,F),this}put(z,...F){return this.#z("PUT",z,F),this}patch(z,...F){return this.#z("PATCH",z,F),this}delete(z,...F){return this.#z("DELETE",z,F),this}}export{B as rateLimit,j as default};
package/dist/router.d.ts DELETED
@@ -1,12 +0,0 @@
1
- import Diesel from "./main";
2
- import type { handlerFunction } from "./types";
3
- declare class Router extends Diesel {
4
- #private;
5
- constructor();
6
- get(path: string, ...handlers: handlerFunction[]): this;
7
- post(path: string, ...handlers: handlerFunction[]): this;
8
- put(path: string, ...handlers: handlerFunction[]): this;
9
- patch(path: string, ...handlers: handlerFunction[]): this;
10
- delete(path: string, ...handlers: handlerFunction[]): this;
11
- }
12
- export default Router;
package/dist/router.js DELETED
@@ -1 +0,0 @@
1
- class B{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class Q{root;constructor(){this.root=new B}insert(F,z){let G=this.root,J=F.split("/").filter(Boolean);if(F==="/"){G.isEndOfWord=!0,G.handler.push(z.handler),G.path=F,G.method.push(z.method);return}for(let U of J){let X=!1,Y=U;if(U.startsWith(":"))X=!0,Y=":";if(!G.children[Y])G.children[Y]=new B;G=G.children[Y],G.isDynamic=X,G.pattern=U}G.isEndOfWord=!0,G.method.push(z.method),G.handler.push(z.handler),G.path=F}search(F,z){let G=this.root,J=F.split("/").filter(Boolean);for(let X of J){let Y=X;if(!G.children[Y])if(G.children[":"])G=G.children[":"];else return null;else G=G.children[Y]}let U=G.method.indexOf(z);if(U!==-1)return{path:G.path,handler:G.handler[U],isDynamic:G.isDynamic,pattern:G.pattern,method:G.method[U]};return{path:G.path,handler:G.handler,isDynamic:G.isDynamic,pattern:G.pattern,method:G.method[U]}}}function D(F,z,G){let J=new Headers,U={},X=!1,Y=null,Z=null,$=null,L,V=200;return{req:F,server:z,url:G,next:()=>{},status(_){return V=_,this},getIP(){return this.server.requestIP(this.req)},async body(){if(!L)L=await b(F);if(L.error)return new Response(JSON.stringify({error:L.error}),{status:400});return L},setHeader(_,E){return J.set(_,E),this},set(_,E){return U[_]=E,this},get(_){return U[_]||null},setAuth(_){return X=_,this},getAuth(){return X},text(_,E){return new Response(_,{status:E??V,headers:J})},json(_,E){return new Response(JSON.stringify(_),{status:E??V,headers:J})},html(_,E){return new Response(Bun.file(_),{status:E??V,headers:J})},file(_,E){return new Response(Bun.file(_),{status:E??V,headers:J})},redirect(_,E){return J.set("Location",_),new Response(null,{status:E??302,headers:J})},getParams(_){if(!$)$=C(F?.routePattern,G?.pathname);return _?$[_]||null:$},getQuery(_){if(!Y)Y=Object.fromEntries(G.searchParams);return _?Y[_]||null:Y},async cookie(_,E,W={}){let A=`${encodeURIComponent(_)}=${encodeURIComponent(E)}`;if(W.maxAge)A+=`; Max-Age=${W.maxAge}`;if(W.expires)A+=`; Expires=${W.expires.toUTCString()}`;if(W.path)A+=`; Path=${W.path}`;if(W.domain)A+=`; Domain=${W.domain}`;if(W.secure)A+="; Secure";if(W.httpOnly)A+="; HttpOnly";if(W.sameSite)A+=`; SameSite=${W.sameSite}`;return J?.append("Set-Cookie",A),this},async getCookie(_){if(!Z){let E=F.headers.get("cookie");if(E)Z=await T(E)}return _?Z[_]||null:Z}}}async function T(F){let z={};if(!F)return z;return F.split(";").forEach((J)=>{let[U,X]=J?.trim()?.split("=");if(U&&X)z[U.trim()]=X.split(" ")[0].trim()}),z}function C(F,z){let G={},J=F.split("/"),[U]=z.split("?"),X=U.split("/");if(J.length!==X.length)return null;return J.forEach((Y,Z)=>{if(Y.startsWith(":")){let $=Y.slice(1);G[$]=X[Z]}}),G}async function b(F){let z=F.headers.get("Content-Type")||"";if(!z)return{};try{if(z.startsWith("application/json"))return await F.json();if(z.startsWith("application/x-www-form-urlencoded")){let G=await F.text();return Object.fromEntries(new URLSearchParams(G))}if(z.startsWith("multipart/form-data")){let G=await F.formData();return v(G)}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}function v(F){let z={};for(let[G,J]of F.entries())z[G]=J;return z}async function j(F,z,G,J){let U=D(F,z,G),X=J.trie.search(G.pathname,F.method);if(!X||X.method!==F.method)return new Response(X?"Method not allowed":`Route not found for ${G.pathname}`,{status:X?405:404});if(X.isDynamic)F.routePattern=X.path;if(J.corsConfig){let Z=await I(F,U,J.corsConfig);if(Z)return Z}if(J.hasOnReqHook&&J.hooks.onRequest)J.hooks.onRequest(U,z);if(J.filters.length>0){let Z=F.routePattern??G.pathname;if(J.filters.includes(Z)===!1)if(J.filterFunction){let L=await J?.filterFunction(U,z);if(L)return L}else return new Response(JSON.stringify({message:"Authentication required"}),{status:400})}if(J.hasMiddleware){let Z=[...J.globalMiddlewares,...J.middlewares.get(G.pathname)||[]];for(let $ of Z){let L=await $(U,z);if(L)return L}}if(J.hasPreHandlerHook&&J.hooks.preHandler){let Z=await J.hooks.preHandler(U);if(Z)return Z}let Y=J.hasPreHandlerHook?await J.hooks.preHandler?.(U):null;if(Y)return Y;try{let Z=await X.handler(U);if(J.hasPostHandlerHook&&J.hooks.postHandler)await J.hooks.postHandler(U);if(J.hasOnSendHook&&J.hooks.onSend){let $=await J.hooks.onSend(U,Z);if($)return $}return Z??new Response("No response from handler",{status:204})}catch(Z){return new Response("Internal Server Error",{status:500})}}async function I(F,z,G={}){let J=F.headers.get("origin")??"*",U=G?.origin,X=G?.allowedHeaders??["Content-Type","Authorization"],Y=G?.methods??["GET","POST","PUT","DELETE","OPTIONS"],Z=G?.credentials??!1,$=G?.exposedHeaders??[];if(z.setHeader("Access-Control-Allow-Methods",Y),z.setHeader("Access-Control-Allow-Headers",X),z.setHeader("Access-Control-Allow-Credentials",Z),$.length)z.setHeader("Access-Control-Expose-Headers",$);if(U==="*")z.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(U))if(J&&U.includes(J))z.setHeader("Access-Control-Allow-Origin",J);else if(U.includes("*"))z.setHeader("Access-Control-Allow-Origin","*");else return z.status(403).json({message:"CORS not allowed"});else if(typeof U==="string")if(J===U)z.setHeader("Access-Control-Allow-Origin",J);else return z.status(403).json({message:"CORS not allowed"});else return z.status(403).json({message:"CORS not allowed"});if(z.setHeader("Access-Control-Allow-Origin",J),F.method==="OPTIONS")return z.setHeader("Access-Control-Max-Age","86400"),z.status(204).text("");return null}function M(F){let{time:z=60000,max:G=100,message:J="Rate limit exceeded. Please try again later."}=F,U=new Map;return(X)=>{let Y=new Date,Z=X.getIP().address;if(!U.has(Z))U.set(Z,{count:0,startTime:Y});let $=U.get(Z);if($)if(Y-$.startTime>z)$.count=1,$.startTime=Y;else $.count++;if($&&$.count>G)return X.status(429).json({error:J});X.next()}}class K{routes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hooks;corsConfig;filters;filterFunction;constructor(){this.routes=[],this.filters=[],this.filterFunction=null,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new Q,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null}}filter(){return{routeMatcher:(...F)=>{return this.routes=F.sort(),this.filter()},permitAll:()=>{for(let F of this?.routes)this.filters.push(F);return this.filter()},require:(F)=>{if(!F||typeof F!=="function")return new Response(JSON.stringify({message:"Authentication required"}),{status:400});this.filterFunction=F}}}cors(F){this.corsConfig=F}addHooks(F,z){if(typeof F!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(F))this.hooks[F]=z;else throw new Error(`Unknown hook type: ${F}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[F,z]of this.middlewares.entries())if(z.length>0){this.hasMiddleware=!0;break}if(this.hooks.onRequest)this.hasOnReqHook=!0;if(this.hooks.preHandler)this.hasPreHandlerHook=!0;if(this.hooks.postHandler)this.hasPostHandlerHook=!0;if(this.hooks.onSend)this.hasOnSendHook=!0}listen(F,z,{sslCert:G=null,sslKey:J=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof F!=="number")throw new Error("Port must be a numeric value");this.compile();let U=this,X={port:F,fetch:async(Z,$)=>{let L=new URL(Z.url);try{return await j(Z,$,L,this)}catch(V){return new Response("Internal Server Error",{status:500})}},onClose(){console.log("Server is shutting down...")}};if(G&&J)X.certFile=G,X.keyFile=J;let Y=Bun.serve(X);if(typeof z==="function")return z();if(G&&J)console.log(`HTTPS server is running on https://localhost:${F}`);else console.log(`HTTP server is running on http://localhost:${F}`);return Y}register(F,z){if(typeof F!=="string")throw new Error("path must be a string");if(typeof z!=="object")throw new Error("handler parameter should be a instance of router object",z);let G=Object.entries(z.trie.root.children);z.trie.root.subMiddlewares.forEach((J,U)=>{if(!this.middlewares.has(F+U))this.middlewares.set(F+U,[]);J?.forEach((X)=>{if(!this.middlewares.get(F+U)?.includes(X))this.middlewares.get(F+U)?.push(X)})});for(let[J,U]of G){let X=F+U?.path,Y=U.handler[0],Z=U.method[0];this.trie.insert(X,{handler:Y,method:Z})}z.trie=new Q}#z(F,z,G){if(typeof z!=="string")throw new Error("Path must be a string type");if(typeof F!=="string")throw new Error("method must be a string type");let J=G.slice(0,-1),U=G[G.length-1];if(!this.middlewares.has(z))this.middlewares.set(z,[]);J.forEach((X)=>{if(z==="/"){if(!this.globalMiddlewares.includes(X))this.globalMiddlewares.push(X)}else if(!this.middlewares.get(z)?.includes(X))this.middlewares.get(z)?.push(X)}),this.trie.insert(z,{handler:U,method:F})}use(F,z){if(typeof F==="function"){if(!this.globalMiddlewares.includes(F))this.globalMiddlewares.push(F);return}let G=F;if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(z){if(!this.middlewares.get(G)?.includes(z))this.middlewares.get(G)?.push(z)}}get(F,...z){return this.#z("GET",F,z),this}post(F,...z){return this.#z("POST",F,z),this}put(F,...z){return this.#z("PUT",F,z),this}patch(F,...z){return this.#z("PATCH",F,z),this}delete(F,...z){return this.#z("DELETE",F,z),this}}class N extends K{constructor(){super()}#z(F,z,G){if(!this.trie.root.subMiddlewares.has(z))this.trie.root.subMiddlewares.set(z,[]);let J=G.slice(0,-1),U=this.trie.root.subMiddlewares.get(z);J.forEach((Y)=>{if(!U?.includes(Y))U?.push(Y)});let X=G[G.length-1];this.trie.insert(z,{handler:X,method:F})}get(F,...z){return this.#z("GET",F,z),this}post(F,...z){return this.#z("POST",F,z),this}put(F,...z){return this.#z("PUT",F,z),this}patch(F,...z){return this.#z("PATCH",F,z),this}delete(F,...z){return this.#z("DELETE",F,z),this}}var x=N;export{x as default};
package/dist/trie.js DELETED
@@ -1 +0,0 @@
1
- class C{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class E{root;constructor(){this.root=new C}insert(w,z){let b=this.root,B=w.split("/").filter(Boolean);if(w==="/"){b.isEndOfWord=!0,b.handler.push(z.handler),b.path=w,b.method.push(z.method);return}for(let j of B){let A=!1,q=j;if(j.startsWith(":"))A=!0,q=":";if(!b.children[q])b.children[q]=new C;b=b.children[q],b.isDynamic=A,b.pattern=j}b.isEndOfWord=!0,b.method.push(z.method),b.handler.push(z.handler),b.path=w}search(w,z){let b=this.root,B=w.split("/").filter(Boolean);for(let A of B){let q=A;if(!b.children[q])if(b.children[":"])b=b.children[":"];else return null;else b=b.children[q]}let j=b.method.indexOf(z);if(j!==-1)return{path:b.path,handler:b.handler[j],isDynamic:b.isDynamic,pattern:b.pattern,method:b.method[j]};return{path:b.path,handler:b.handler,isDynamic:b.isDynamic,pattern:b.pattern,method:b.method[j]}}}export{E as default};