diesel-core 0.0.7 → 0.0.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.
@@ -0,0 +1 @@
1
+ if you changes code OR fixing bugs so after doing make sure to run bun build.js
package/build.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // build.js
2
2
  await Bun.build({
3
3
  entrypoints: [
4
- './src/server.js',
5
- './src/ctx.js',
6
- './src/handleRequest.js',
7
- './src/trie.js',
8
- './src/router.js'
4
+ './src/main.ts',
5
+ './src/ctx.ts',
6
+ './src/handleRequest.ts',
7
+ './src/trie.ts',
8
+ './src/router.ts'
9
9
  ],
10
10
  outdir: './dist',
11
11
  minify: true, // Enable minification
package/dist/ctx.js CHANGED
@@ -1 +1 @@
1
- async function H(G){const F={};if(!G)return F;return G.split(";").forEach((L)=>{const[X,M]=L.trim().split("=");F[X]=M.split(" ")[0]}),F}function K(G,F){const z={},L=G.split("/"),[X]=F.split("?"),M=X.split("/");if(L.length!==M.length)return null;return L.forEach((U,Y)=>{if(U.startsWith(":")){const Z=U.slice(1);z[Z]=M[Y]}}),z}async function W(G){const F=G.headers.get("Content-Type")||"";if(!F)return{};try{if(F.startsWith("application/json"))return await G.json();if(F.startsWith("application/x-www-form-urlencoded")){const z=await G.text();return Object.fromEntries(new URLSearchParams(z))}if(F.startsWith("multipart/form-data")){const z=await G.formData();return O(z)}return new Response({error:"Unknown request body type"})}catch(z){return new Response({error:"Invalid request body format"})}}function O(G){const F={};for(let[z,L]of G.entries())F[z]=L;return F}function $(G,F){let z={},L={},X=!1,M=null,U=null,Y=null,Z=null,J=200;return{req:G,url:F,next:()=>{},status(w){return J=w,this},async body(){if(!Z)Z=await W(G);return Z},setHeader(w,E){return z[w]=E,this},set(w,E){return L[w]=E,this},get(w){return L[w]},setAuth(w){return X=w,this},getAuth(){return X},text(w,E){if(E)J=E;return new Response(w,{status:J,headers:z})},json(w,E){if(E)J=E;return new Response(JSON.stringify(w),{status:J,headers:{"Content-Type":"application/json",...z}})},html(w,E){if(E)J=E;return new Response(Bun.file(w),{status:J,headers:{...z}})},file(w,E){if(E)J=E;return new Response(Bun.file(w),{status:J,headers:{...z}})},redirect(w,E){if(E)J=E;return new Response(null,{status:J,headers:{Location:w,...z}})},getParams(w){if(!Y)Y=K(G.routePattern,F.pathname);return w?Y[w]:Y},getQuery(w){if(!M)M=Object.fromEntries(F.searchParams);return w?M[w]:M},async cookie(w,E,I={}){let R=`${encodeURIComponent(w)}=${encodeURIComponent(E)}`;if(I.maxAge)R+=`; Max-Age=${I.maxAge}`;if(I.expires)R+=`; Expires=${I.expires.toUTCString()}`;if(I.path)R+=`; Path=${I.path}`;if(I.domain)R+=`; Domain=${I.domain}`;if(I.secure)R+="; Secure";if(I.httpOnly)R+="; HttpOnly";if(I.sameSite)R+=`; SameSite=${I.sameSite}`;if(z["Set-Cookie"]){const _=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];_.push(R),z["Set-Cookie"]=_}else z["Set-Cookie"]=R;return this},async getCookie(w){if(!U)U=await H(G.headers.get("cookie"));return w?U[w]:U}}}export{$ as default};
1
+ var w=(I,F)=>()=>(F||I((F={exports:{}}).exports,F),F.exports);var B=w((W)=>{function A(I,F){let E={},J={},X=!1,L=null,M=null,$=null,Y,R=200;return{req:I,url:F,next:()=>{},status(z){return R=z,this},body(){return K(this,void 0,void 0,function*(){if(!Y)Y=yield T(I);if(Y.error)return new Response(JSON.stringify({error:Y.error}),{status:400,headers:{"Content-Type":"application/json"}});return Y})},setHeader(z,G){return E[z]=G,this},set(z,G){return J[z]=G,this},get(z){return J[z]||null},setAuth(z){return X=z,this},getAuth(){return X},text(z,G){if(G)R=G;return new Response(z,{status:R,headers:E})},json(z,G){if(G)R=G;return new Response(JSON.stringify(z),{status:R,headers:Object.assign({"Content-Type":"application/json"},E)})},html(z,G){if(G)R=G;return new Response(Bun.file(z),{status:R,headers:Object.assign({},E)})},file(z,G){if(G)R=G;return new Response(Bun.file(z),{status:R,headers:Object.assign({},E)})},redirect(z,G){if(G)R=G;return new Response(null,{status:R,headers:Object.assign({Location:z},E)})},getParams(z){if(!$)$=Q(I===null||I===void 0?void 0:I.routePattern,F===null||F===void 0?void 0:F.pathname);return z?$[z]||null:$},getQuery(z){if(!L)L=Object.fromEntries(F.searchParams);return z?L[z]||null:L},cookie(z,G){return K(this,arguments,void 0,function*(H,V,U={}){let Z=`${encodeURIComponent(H)}=${encodeURIComponent(V)}`;if(U.maxAge)Z+=`; Max-Age=${U.maxAge}`;if(U.expires)Z+=`; Expires=${U.expires.toUTCString()}`;if(U.path)Z+=`; Path=${U.path}`;if(U.domain)Z+=`; Domain=${U.domain}`;if(U.secure)Z+="; Secure";if(U.httpOnly)Z+="; HttpOnly";if(U.sameSite)Z+=`; SameSite=${U.sameSite}`;if(E["Set-Cookie"]){const O=Array.isArray(E["Set-Cookie"])?E["Set-Cookie"]:[E["Set-Cookie"]];O.push(Z),E["Set-Cookie"]=O}else E["Set-Cookie"]=Z;return this})},getCookie(z){return K(this,void 0,void 0,function*(){if(!M){const G=I.headers.get("cookie");if(G)M=yield D(G)}return z?M[z]||null:M})}}}function D(I){return K(this,void 0,void 0,function*(){const F={};if(!I)return F;return I.split(";").forEach((J)=>{var X;const[L,M]=(X=J===null||J===void 0?void 0:J.trim())===null||X===void 0?void 0:X.split("=");if(L&&M)F[L.trim()]=M.split(" ")[0].trim()}),F})}function Q(I,F){const E={},J=I.split("/"),[X]=F.split("?"),L=X.split("/");if(J.length!==L.length)return null;return J.forEach((M,$)=>{if(M.startsWith(":")){const Y=M.slice(1);E[Y]=L[$]}}),E}function T(I){return K(this,void 0,void 0,function*(){const F=I.headers.get("Content-Type")||"";if(!F)return{};try{if(F.startsWith("application/json"))return yield I.json();if(F.startsWith("application/x-www-form-urlencoded")){const E=yield I.text();return Object.fromEntries(new URLSearchParams(E))}if(F.startsWith("multipart/form-data")){const E=yield I.formData();return b(E)}return{error:"Unknown request body type"}}catch(E){return{error:"Invalid request body format"}}})}function b(I){const F={};for(let[E,J]of I.entries())F[E]=J;return F}var K=W&&W.__awaiter||function(I,F,E,J){function X(L){return L instanceof E?L:new E(function(M){M(L)})}return new(E||(E=Promise))(function(L,M){function $(z){try{R(J.next(z))}catch(G){M(G)}}function Y(z){try{R(J.throw(z))}catch(G){M(G)}}function R(z){z.done?L(z.value):X(z.value).then($,Y)}R((J=J.apply(I,F||[])).next())})};Object.defineProperty(W,"__esModule",{value:!0});W.default=A});export default B();
@@ -1 +1 @@
1
- async function A(G){const F={};if(!G)return F;return G.split(";").forEach((J)=>{const[U,L]=J.trim().split("=");F[U]=L.split(" ")[0]}),F}function V(G,F){const z={},J=G.split("/"),[U]=F.split("?"),L=U.split("/");if(J.length!==L.length)return null;return J.forEach((X,$)=>{if(X.startsWith(":")){const K=X.slice(1);z[K]=L[$]}}),z}async function B(G){const F=G.headers.get("Content-Type")||"";if(!F)return{};try{if(F.startsWith("application/json"))return await G.json();if(F.startsWith("application/x-www-form-urlencoded")){const z=await G.text();return Object.fromEntries(new URLSearchParams(z))}if(F.startsWith("multipart/form-data")){const z=await G.formData();return j(z)}return new Response({error:"Unknown request body type"})}catch(z){return new Response({error:"Invalid request body format"})}}function j(G){const F={};for(let[z,J]of G.entries())F[z]=J;return F}function M(G,F){let z={},J={},U=!1,L=null,X=null,$=null,K=null,Z=200;return{req:G,url:F,next:()=>{},status(E){return Z=E,this},async body(){if(!K)K=await B(G);return K},setHeader(E,I){return z[E]=I,this},set(E,I){return J[E]=I,this},get(E){return J[E]},setAuth(E){return U=E,this},getAuth(){return U},text(E,I){if(I)Z=I;return new Response(E,{status:Z,headers:z})},json(E,I){if(I)Z=I;return new Response(JSON.stringify(E),{status:Z,headers:{"Content-Type":"application/json",...z}})},html(E,I){if(I)Z=I;return new Response(Bun.file(E),{status:Z,headers:{...z}})},file(E,I){if(I)Z=I;return new Response(Bun.file(E),{status:Z,headers:{...z}})},redirect(E,I){if(I)Z=I;return new Response(null,{status:Z,headers:{Location:E,...z}})},getParams(E){if(!$)$=V(G.routePattern,F.pathname);return E?$[E]:$},getQuery(E){if(!L)L=Object.fromEntries(F.searchParams);return E?L[E]:L},async cookie(E,I,Y={}){let _=`${encodeURIComponent(E)}=${encodeURIComponent(I)}`;if(Y.maxAge)_+=`; Max-Age=${Y.maxAge}`;if(Y.expires)_+=`; Expires=${Y.expires.toUTCString()}`;if(Y.path)_+=`; Path=${Y.path}`;if(Y.domain)_+=`; Domain=${Y.domain}`;if(Y.secure)_+="; Secure";if(Y.httpOnly)_+="; HttpOnly";if(Y.sameSite)_+=`; SameSite=${Y.sameSite}`;if(z["Set-Cookie"]){const O=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];O.push(_),z["Set-Cookie"]=O}else z["Set-Cookie"]=_;return this},async getCookie(E){if(!X)X=await A(G.headers.get("cookie"));return E?X[E]:X}}}async function N(G,F){for(let z of G){const J=await z(F);if(J)return J}}var W={};async function D(G,F,z){const J=M(G,F);if(z.hasOnReqHook)await z.hooks.onRequest(J);if(z.hasMiddleware){const L=[...z.globalMiddlewares,...z.middlewares.get(F.pathname)||[]],X=await N(L,J);if(X)return X}let U;if(W[F.pathname+G.method])U=W[F.pathname+G.method];else U=z.trie.search(F.pathname,G.method),W[F.pathname+G.method]=U;if(!U||!U.handler)return new Response(`Route not found for ${F.pathname}`,{status:404});if(U.method!==G.method)return new Response("Method not allowed",{status:405});if(U.isDynamic)G.routePattern=U.path;if(z.hasPreHandlerHook){const L=await z.hooks.preHandler(J);if(L)return L}try{const L=await U.handler(J);if(z.hasPostHandlerHook)await z.hooks.postHandler(J);if(z.hasOnSendHook){const X=await z.hooks.onSend(L,J);if(X)return X}return L??new Response("No response from handler",{status:204})}catch(L){return new Response("Internal Server Error",{status:500})}}export{D as default};
1
+ var B=(F,G)=>()=>(G||F((G={exports:{}}).exports,G),G.exports);var D=B((V)=>{function A(F,G){let z={},J={},X=!1,I=null,U=null,K=null,$,Y=200;return{req:F,url:G,next:()=>{},status(E){return Y=E,this},body(){return O(this,void 0,void 0,function*(){if(!$)$=yield H(F);if($.error)return new Response(JSON.stringify({error:$.error}),{status:400,headers:{"Content-Type":"application/json"}});return $})},setHeader(E,L){return z[E]=L,this},set(E,L){return J[E]=L,this},get(E){return J[E]||null},setAuth(E){return X=E,this},getAuth(){return X},text(E,L){if(L)Y=L;return new Response(E,{status:Y,headers:z})},json(E,L){if(L)Y=L;return new Response(JSON.stringify(E),{status:Y,headers:Object.assign({"Content-Type":"application/json"},z)})},html(E,L){if(L)Y=L;return new Response(Bun.file(E),{status:Y,headers:Object.assign({},z)})},file(E,L){if(L)Y=L;return new Response(Bun.file(E),{status:Y,headers:Object.assign({},z)})},redirect(E,L){if(L)Y=L;return new Response(null,{status:Y,headers:Object.assign({Location:E},z)})},getParams(E){if(!K)K=f(F===null||F===void 0?void 0:F.routePattern,G===null||G===void 0?void 0:G.pathname);return E?K[E]||null:K},getQuery(E){if(!I)I=Object.fromEntries(G.searchParams);return E?I[E]||null:I},cookie(E,L){return O(this,arguments,void 0,function*(R,b,Z={}){let M=`${encodeURIComponent(R)}=${encodeURIComponent(b)}`;if(Z.maxAge)M+=`; Max-Age=${Z.maxAge}`;if(Z.expires)M+=`; Expires=${Z.expires.toUTCString()}`;if(Z.path)M+=`; Path=${Z.path}`;if(Z.domain)M+=`; Domain=${Z.domain}`;if(Z.secure)M+="; Secure";if(Z.httpOnly)M+="; HttpOnly";if(Z.sameSite)M+=`; SameSite=${Z.sameSite}`;if(z["Set-Cookie"]){const T=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];T.push(M),z["Set-Cookie"]=T}else z["Set-Cookie"]=M;return this})},getCookie(E){return O(this,void 0,void 0,function*(){if(!U){const L=F.headers.get("cookie");if(L)U=yield C(L)}return E?U[E]||null:U})}}}function C(F){return O(this,void 0,void 0,function*(){const G={};if(!F)return G;return F.split(";").forEach((J)=>{var X;const[I,U]=(X=J===null||J===void 0?void 0:J.trim())===null||X===void 0?void 0:X.split("=");if(I&&U)G[I.trim()]=U.split(" ")[0].trim()}),G})}function f(F,G){const z={},J=F.split("/"),[X]=G.split("?"),I=X.split("/");if(J.length!==I.length)return null;return J.forEach((U,K)=>{if(U.startsWith(":")){const $=U.slice(1);z[$]=I[K]}}),z}function H(F){return O(this,void 0,void 0,function*(){const G=F.headers.get("Content-Type")||"";if(!G)return{};try{if(G.startsWith("application/json"))return yield F.json();if(G.startsWith("application/x-www-form-urlencoded")){const z=yield F.text();return Object.fromEntries(new URLSearchParams(z))}if(G.startsWith("multipart/form-data")){const z=yield F.formData();return j(z)}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}})}function j(F){const G={};for(let[z,J]of F.entries())G[z]=J;return G}var O=V&&V.__awaiter||function(F,G,z,J){function X(I){return I instanceof z?I:new z(function(U){U(I)})}return new(z||(z=Promise))(function(I,U){function K(E){try{Y(J.next(E))}catch(L){U(L)}}function $(E){try{Y(J.throw(E))}catch(L){U(L)}}function Y(E){E.done?I(E.value):X(E.value).then(K,$)}Y((J=J.apply(F,G||[])).next())})};Object.defineProperty(V,"__esModule",{value:!0});V.default=A});var S=B((W)=>{function P(F,G,z){return N(this,void 0,void 0,function*(){const J=_.default(F,G);if(z.hasOnReqHook)yield z.hooks.onRequest(J);if(z.hasMiddleware){const I=[...z.globalMiddlewares,...z.middlewares.get(G.pathname)||[]],U=yield y(I,J);if(U)return U}let X;if(Q[G.pathname+F.method])X=Q[G.pathname+F.method];else X=z.trie.search(G.pathname,F.method),Q[G.pathname+F.method]=X;if(!X||!X.handler)return new Response(`Route not found for ${G.pathname}`,{status:404});if(X.method!==F.method)return new Response("Method not allowed",{status:405});if(X.isDynamic)F.routePattern=X.path;if(z.hasPreHandlerHook){const I=yield z.hooks.preHandler(J);if(I)return I}try{const I=yield X.handler(J);if(z.hasPostHandlerHook)yield z.hooks.postHandler(J);if(z.hasOnSendHook){const U=yield z.hooks.onSend(I,J);if(U)return U}return I!==null&&I!==void 0?I:new Response("No response from handler",{status:204})}catch(I){return new Response("Internal Server Error",{status:500})}})}function y(F,G){return N(this,void 0,void 0,function*(){for(let z of F){const J=yield z(G);if(J)return J}})}var N=W&&W.__awaiter||function(F,G,z,J){function X(I){return I instanceof z?I:new z(function(U){U(I)})}return new(z||(z=Promise))(function(I,U){function K(E){try{Y(J.next(E))}catch(L){U(L)}}function $(E){try{Y(J.throw(E))}catch(L){U(L)}}function Y(E){E.done?I(E.value):X(E.value).then(K,$)}Y((J=J.apply(F,G||[])).next())})},w=W&&W.__importDefault||function(F){return F&&F.__esModule?F:{default:F}};Object.defineProperty(W,"__esModule",{value:!0});W.default=P;var _=w(D()),Q={}});export default S();
package/dist/main.js ADDED
@@ -0,0 +1 @@
1
+ var C=(J,L)=>()=>(L||J((L={exports:{}}).exports,L),L.exports);var S=C((D)=>{Object.defineProperty(D,"__esModule",{value:!0});class O{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class j{constructor(){this.root=new O}insert(J,L){let z=this.root;const U=J.split("/").filter(Boolean);if(J==="/"){z.isEndOfWord=!0,z.handler.push(L.handler),z.path=J,z.method.push(L.method);return}for(let X of U){let Y=!1,Z=X;if(X.startsWith(":"))Y=!0,Z=":";if(!z.children[Z])z.children[Z]=new O;z=z.children[Z],z.isDynamic=Y,z.pattern=X}z.isEndOfWord=!0,z.method.push(L.method),z.handler.push(L.handler),z.path=J}search(J,L){let z=this.root;const U=J.split("/").filter(Boolean);for(let Y of U){let Z=Y;if(!z.children[Z])if(z.children[":"])z=z.children[":"];else return null;else z=z.children[Z]}let X=z.method.indexOf(L);if(X!==-1)return{path:z.path,handler:z.handler[X],isDynamic:z.isDynamic,pattern:z.pattern,method:z.method[X]};return{path:z.path,handler:z.handler,isDynamic:z.isDynamic,pattern:z.pattern,method:z.method[X]}}}D.default=j});var H=C((I)=>{function k(J,L){let z={},U={},X=!1,Y=null,Z=null,W=null,G,V=200;return{req:J,url:L,next:()=>{},status($){return V=$,this},body(){return T(this,void 0,void 0,function*(){if(!G)G=yield c(J);if(G.error)return new Response(JSON.stringify({error:G.error}),{status:400,headers:{"Content-Type":"application/json"}});return G})},setHeader($,E){return z[$]=E,this},set($,E){return U[$]=E,this},get($){return U[$]||null},setAuth($){return X=$,this},getAuth(){return X},text($,E){if(E)V=E;return new Response($,{status:V,headers:z})},json($,E){if(E)V=E;return new Response(JSON.stringify($),{status:V,headers:Object.assign({"Content-Type":"application/json"},z)})},html($,E){if(E)V=E;return new Response(Bun.file($),{status:V,headers:Object.assign({},z)})},file($,E){if(E)V=E;return new Response(Bun.file($),{status:V,headers:Object.assign({},z)})},redirect($,E){if(E)V=E;return new Response(null,{status:V,headers:Object.assign({Location:$},z)})},getParams($){if(!W)W=m(J===null||J===void 0?void 0:J.routePattern,L===null||L===void 0?void 0:L.pathname);return $?W[$]||null:W},getQuery($){if(!Y)Y=Object.fromEntries(L.searchParams);return $?Y[$]||null:Y},cookie($,E){return T(this,arguments,void 0,function*(f,v,Q={}){let F=`${encodeURIComponent(f)}=${encodeURIComponent(v)}`;if(Q.maxAge)F+=`; Max-Age=${Q.maxAge}`;if(Q.expires)F+=`; Expires=${Q.expires.toUTCString()}`;if(Q.path)F+=`; Path=${Q.path}`;if(Q.domain)F+=`; Domain=${Q.domain}`;if(Q.secure)F+="; Secure";if(Q.httpOnly)F+="; HttpOnly";if(Q.sameSite)F+=`; SameSite=${Q.sameSite}`;if(z["Set-Cookie"]){const R=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];R.push(F),z["Set-Cookie"]=R}else z["Set-Cookie"]=F;return this})},getCookie($){return T(this,void 0,void 0,function*(){if(!Z){const E=J.headers.get("cookie");if(E)Z=yield _(E)}return $?Z[$]||null:Z})}}}function _(J){return T(this,void 0,void 0,function*(){const L={};if(!J)return L;return J.split(";").forEach((U)=>{var X;const[Y,Z]=(X=U===null||U===void 0?void 0:U.trim())===null||X===void 0?void 0:X.split("=");if(Y&&Z)L[Y.trim()]=Z.split(" ")[0].trim()}),L})}function m(J,L){const z={},U=J.split("/"),[X]=L.split("?"),Y=X.split("/");if(U.length!==Y.length)return null;return U.forEach((Z,W)=>{if(Z.startsWith(":")){const G=Z.slice(1);z[G]=Y[W]}}),z}function c(J){return T(this,void 0,void 0,function*(){const L=J.headers.get("Content-Type")||"";if(!L)return{};try{if(L.startsWith("application/json"))return yield J.json();if(L.startsWith("application/x-www-form-urlencoded")){const z=yield J.text();return Object.fromEntries(new URLSearchParams(z))}if(L.startsWith("multipart/form-data")){const z=yield J.formData();return h(z)}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}})}function h(J){const L={};for(let[z,U]of J.entries())L[z]=U;return L}var T=I&&I.__awaiter||function(J,L,z,U){function X(Y){return Y instanceof z?Y:new z(function(Z){Z(Y)})}return new(z||(z=Promise))(function(Y,Z){function W($){try{V(U.next($))}catch(E){Z(E)}}function G($){try{V(U.throw($))}catch(E){Z(E)}}function V($){$.done?Y($.value):X($.value).then(W,G)}V((U=U.apply(J,L||[])).next())})};Object.defineProperty(I,"__esModule",{value:!0});I.default=k});var q=C((B)=>{function i(J,L,z){return w(this,void 0,void 0,function*(){const U=p.default(J,L);if(z.hasOnReqHook)yield z.hooks.onRequest(U);if(z.hasMiddleware){const Y=[...z.globalMiddlewares,...z.middlewares.get(L.pathname)||[]],Z=yield n(Y,U);if(Z)return Z}let X;if(b[L.pathname+J.method])X=b[L.pathname+J.method];else X=z.trie.search(L.pathname,J.method),b[L.pathname+J.method]=X;if(!X||!X.handler)return new Response(`Route not found for ${L.pathname}`,{status:404});if(X.method!==J.method)return new Response("Method not allowed",{status:405});if(X.isDynamic)J.routePattern=X.path;if(z.hasPreHandlerHook){const Y=yield z.hooks.preHandler(U);if(Y)return Y}try{const Y=yield X.handler(U);if(z.hasPostHandlerHook)yield z.hooks.postHandler(U);if(z.hasOnSendHook){const Z=yield z.hooks.onSend(Y,U);if(Z)return Z}return Y!==null&&Y!==void 0?Y:new Response("No response from handler",{status:204})}catch(Y){return new Response("Internal Server Error",{status:500})}})}function n(J,L){return w(this,void 0,void 0,function*(){for(let z of J){const U=yield z(L);if(U)return U}})}var w=B&&B.__awaiter||function(J,L,z,U){function X(Y){return Y instanceof z?Y:new z(function(Z){Z(Y)})}return new(z||(z=Promise))(function(Y,Z){function W($){try{V(U.next($))}catch(E){Z(E)}}function G($){try{V(U.throw($))}catch(E){Z(E)}}function V($){$.done?Y($.value):X($.value).then(W,G)}V((U=U.apply(J,L||[])).next())})},u=B&&B.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(B,"__esModule",{value:!0});B.default=i;var p=u(H()),b={}});var o=C((M)=>{var l=M&&M.__awaiter||function(J,L,z,U){function X(Y){return Y instanceof z?Y:new z(function(Z){Z(Y)})}return new(z||(z=Promise))(function(Y,Z){function W($){try{V(U.next($))}catch(E){Z(E)}}function G($){try{V(U.throw($))}catch(E){Z(E)}}function V($){$.done?Y($.value):X($.value).then(W,G)}V((U=U.apply(J,L||[])).next())})},N=M&&M.__classPrivateFieldGet||function(J,L,z,U){if(z==="a"&&!U)throw new TypeError("Private accessor was defined without a getter");if(typeof L==="function"?J!==L||!U:!L.has(J))throw new TypeError("Cannot read private member from an object whose class did not declare it");return z==="m"?U:z==="a"?U.call(J):U?U.value:L.get(J)},P=M&&M.__importDefault||function(J){return J&&J.__esModule?J:{default:J}},K,A;Object.defineProperty(M,"__esModule",{value:!0});var y=P(S()),d=P(q());class x{constructor(){K.add(this),this.routes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new y.default,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}}addHooks(J,L){if(typeof J!=="string")throw new Error("hookName must be a string");if(typeof L!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(J))this.hooks[J]=L;else throw new Error(`Unknown hook type: ${J}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[J,L]of this.middlewares.entries())if(L.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(J,L,{sslCert:z=null,sslKey:U=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof J!=="number")throw new Error("Port must be a numeric value");this.compile();const X={port:J,fetch:(Z)=>l(this,void 0,void 0,function*(){const W=new URL(Z.url);try{return yield d.default(Z,W,this)}catch(G){return new Response("Internal Server Error",{status:500})}}),onClose(){console.log("Server is shutting down...")}};if(z&&U)X.certFile=z,X.keyFile=U;const Y=Bun.serve(X);if(typeof L==="function")return L();if(z&&U)console.log(`HTTPS server is running on https://localhost:${J}`);else console.log(`HTTP server is running on http://localhost:${J}`);return Y}register(J,L){if(typeof J!=="string")throw new Error("path must be a string");if(typeof L!=="object")throw new Error("handler parameter should be a instance of router object",L);const z=Object.entries(L.trie.root.children);L.trie.root.subMiddlewares.forEach((U,X)=>{if(!this.middlewares.has(J+X))this.middlewares.set(J+X,[]);U===null||U===void 0||U.forEach((Y)=>{var Z,W;if(!((Z=this.middlewares.get(J+X))===null||Z===void 0?void 0:Z.includes(Y)))(W=this.middlewares.get(J+X))===null||W===void 0||W.push(Y)})});for(let[U,X]of z){const Y=J+(X===null||X===void 0?void 0:X.path),Z=X.handler[0],W=X.method[0];this.trie.insert(Y,{handler:Z,method:W})}L.trie=new y.default}use(J,L){var z,U;if(typeof J==="function"){if(!this.globalMiddlewares.includes(J))return this.globalMiddlewares.push(J)}const X=J;if(!this.middlewares.has(X))this.middlewares.set(X,[]);if(!((z=this.middlewares.get(X))===null||z===void 0?void 0:z.includes(L)))(U=this.middlewares.get(X))===null||U===void 0||U.push(L)}get(J,...L){return N(this,K,"m",A).call(this,"GET",J,L),this}post(J,...L){return N(this,K,"m",A).call(this,"POST",J,L),this}put(J,...L){return N(this,K,"m",A).call(this,"PUT",J,L),this}patch(J,...L){return N(this,K,"m",A).call(this,"PATCH",J,L),this}delete(J,...L){return N(this,K,"m",A).call(this,"DELETE",J,L),this}}K=new WeakSet,A=function J(L,z,U){if(typeof z!=="string")throw new Error("Path must be a string type");if(typeof L!=="string")throw new Error("method must be a string type");const X=U.slice(0,-1),Y=U[U.length-1];if(!this.middlewares.has(z))this.middlewares.set(z,[]);X.forEach((Z)=>{var W,G;if(z==="/"){if(!this.globalMiddlewares.includes(Z))this.globalMiddlewares.push(Z)}else if(!((W=this.middlewares.get(z))===null||W===void 0?void 0:W.includes(Z)))(G=this.middlewares.get(z))===null||G===void 0||G.push(Z)}),this.trie.insert(z,{handler:Y,method:L})};M.default=x});export default o();
package/dist/router.js CHANGED
@@ -1 +1 @@
1
- class V{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class M{constructor(){this.root=new V}insert(L,G){let E=this.root;const z=L.split("/").filter(Boolean);if(L==="/"){E.isEndOfWord=!0,E.handler.push(G.handler),E.path=L,E.method.push(G.method);return}for(let U of z){let F=!1,X=U;if(U.startsWith(":"))F=!0,X=":";if(!E.children[X])E.children[X]=new V;E=E.children[X],E.isDynamic=F,E.pattern=U}E.isEndOfWord=!0,E.method.push(G.method),E.handler.push(G.handler),E.path=L}insertMidl(L){if(!this.root.subMiddlewares.has(L))this.root.subMiddlewares.set(L)}search(L,G){let E=this.root;const z=L.split("/").filter(Boolean);for(let F of z){let X=F;if(!E.children[X])if(E.children[":"])E=E.children[":"];else return null;else E=E.children[X]}let U=E.method.indexOf(G);if(U!==-1)return{path:E.path,handler:E.handler[U],isDynamic:E.isDynamic,pattern:E.pattern,method:E.method[U]};return{path:E.path,handler:E.handler,isDynamic:E.isDynamic,pattern:E.pattern,method:E.method[U]}}getAllRoutes(){const L=[],G=(E,z)=>{if(E.isEndOfWord)L.push({path:z,handler:E.handler,isImportant:E.isImportant,isDynamic:E.isDynamic,pattern:E.pattern});for(let U in E.children){const F=E.children[U],X=z+(U===":"?"/:"+F.pattern:"/"+U);G(F,X)}};return G(this.root,""),L}}async function v(L){const G={};if(!L)return G;return L.split(";").forEach((z)=>{const[U,F]=z.trim().split("=");G[U]=F.split(" ")[0]}),G}function N(L,G){const E={},z=L.split("/"),[U]=G.split("?"),F=U.split("/");if(z.length!==F.length)return null;return z.forEach((X,$)=>{if(X.startsWith(":")){const A=X.slice(1);E[A]=F[$]}}),E}async function I(L){const G=L.headers.get("Content-Type")||"";if(!G)return{};try{if(G.startsWith("application/json"))return await L.json();if(G.startsWith("application/x-www-form-urlencoded")){const E=await L.text();return Object.fromEntries(new URLSearchParams(E))}if(G.startsWith("multipart/form-data")){const E=await L.formData();return C(E)}return new Response({error:"Unknown request body type"})}catch(E){return new Response({error:"Invalid request body format"})}}function C(L){const G={};for(let[E,z]of L.entries())G[E]=z;return G}function B(L,G){let E={},z={},U=!1,F=null,X=null,$=null,A=null,_=200;return{req:L,url:G,next:()=>{},status(J){return _=J,this},async body(){if(!A)A=await I(L);return A},setHeader(J,Y){return E[J]=Y,this},set(J,Y){return z[J]=Y,this},get(J){return z[J]},setAuth(J){return U=J,this},getAuth(){return U},text(J,Y){if(Y)_=Y;return new Response(J,{status:_,headers:E})},json(J,Y){if(Y)_=Y;return new Response(JSON.stringify(J),{status:_,headers:{"Content-Type":"application/json",...E}})},html(J,Y){if(Y)_=Y;return new Response(Bun.file(J),{status:_,headers:{...E}})},file(J,Y){if(Y)_=Y;return new Response(Bun.file(J),{status:_,headers:{...E}})},redirect(J,Y){if(Y)_=Y;return new Response(null,{status:_,headers:{Location:J,...E}})},getParams(J){if(!$)$=N(L.routePattern,G.pathname);return J?$[J]:$},getQuery(J){if(!F)F=Object.fromEntries(G.searchParams);return J?F[J]:F},async cookie(J,Y,Z={}){let W=`${encodeURIComponent(J)}=${encodeURIComponent(Y)}`;if(Z.maxAge)W+=`; Max-Age=${Z.maxAge}`;if(Z.expires)W+=`; Expires=${Z.expires.toUTCString()}`;if(Z.path)W+=`; Path=${Z.path}`;if(Z.domain)W+=`; Domain=${Z.domain}`;if(Z.secure)W+="; Secure";if(Z.httpOnly)W+="; HttpOnly";if(Z.sameSite)W+=`; SameSite=${Z.sameSite}`;if(E["Set-Cookie"]){const b=Array.isArray(E["Set-Cookie"])?E["Set-Cookie"]:[E["Set-Cookie"]];b.push(W),E["Set-Cookie"]=b}else E["Set-Cookie"]=W;return this},async getCookie(J){if(!X)X=await v(L.headers.get("cookie"));return J?X[J]:X}}}async function w(L,G){for(let E of L){const z=await E(G);if(z)return z}}var Q={};async function T(L,G,E){const z=B(L,G);if(E.hasOnReqHook)await E.hooks.onRequest(z);if(E.hasMiddleware){const F=[...E.globalMiddlewares,...E.middlewares.get(G.pathname)||[]],X=await w(F,z);if(X)return X}let U;if(Q[G.pathname+L.method])U=Q[G.pathname+L.method];else U=E.trie.search(G.pathname,L.method),Q[G.pathname+L.method]=U;if(!U||!U.handler)return new Response(`Route not found for ${G.pathname}`,{status:404});if(U.method!==L.method)return new Response("Method not allowed",{status:405});if(U.isDynamic)L.routePattern=U.path;if(E.hasPreHandlerHook){const F=await E.hooks.preHandler(z);if(F)return F}try{const F=await U.handler(z);if(E.hasPostHandlerHook)await E.hooks.postHandler(z);if(E.hasOnSendHook){const X=await E.hooks.onSend(F,z);if(X)return X}return F??new Response("No response from handler",{status:204})}catch(F){return new Response("Internal Server Error",{status:500})}}class j{constructor(){this.routes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new M,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}}addHooks(L,G){if(typeof L!=="string")throw new Error("hookName must be a string");if(typeof G!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(L))this.hooks[L]=G;else throw new Error(`Unknown hook type: ${L}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[L,G]of this.middlewares.entries())if(G.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(L,G,{sslCert:E=null,sslKey:z=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof L!=="number")throw new Error("Port must be a numeric value");this.compile();const U={port:L,fetch:async(X)=>{const $=new URL(X.url);try{return await T(X,$,this)}catch(A){return new Response("Internal Server Error",{status:500})}},onClose(){console.log("Server is shutting down...")}};if(E&&z)U.certFile=E,U.keyFile=z;const F=Bun.serve(U);if(typeof G==="function")return G();if(E&&z)console.log(`HTTPS server is running on https://localhost:${L}`);else console.log(`HTTP server is running on http://localhost:${L}`);return F}register(L,G){if(typeof L!=="string")throw new Error("path must be a string");if(typeof G!=="object")throw new Error("handler parameter should be a instance of router object",G);const E=Object.entries(G.trie.root.children);G.trie.root.subMiddlewares.forEach((z,U)=>{if(!this.middlewares.has(L+U))this.middlewares.set(L+U,[]);if(!this.middlewares.get(L+U).includes(...z))this.middlewares.get(L+U).push(...z)});for(let[z,U]of E){const F=L+U?.path,X=U.handler[0],$=U.method[0];this.trie.insert(F,{handler:X,method:$})}G.trie=new M}#E(L,G,E){if(typeof G!=="string")throw new Error("Path must be a string type");if(typeof L!=="string")throw new Error("method must be a string type");const z=E.slice(0,-1);if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(G==="/")z.forEach((F)=>{if(!this.globalMiddlewares.includes(F))this.globalMiddlewares.push(F)});else if(!this.middlewares.get(G).includes(...z))this.middlewares.get(G).push(...z);const U=E[E.length-1];this.trie.insert(G,{handler:U,method:L})}use(L,G){if(typeof L==="function"){if(!this.globalMiddlewares.includes(L))return this.globalMiddlewares.push(L)}const E=L;if(!this.middlewares.has(E))this.middlewares.set(E,[]);if(!this.middlewares.get(E).includes(G))this.middlewares.get(E).push(G)}get(L,...G){return this.#E("GET",L,G),this}post(L,...G){return this.#E("POST",L,G),this}put(L,...G){return this.#E("PUT",L,G),this}patch(L,...G){return this.#E("PATCH",L,G),this}delete(L,...G){return this.#E("DELETE",L,G),this}}var K=j;class D extends K{constructor(){super()}#E(L,G,E){if(!this.trie.root.subMiddlewares.has(G))this.trie.root.subMiddlewares.set(G,[]);const z=E.slice(0,-1);if(!this.trie.root.subMiddlewares.get(G).includes(...z))this.trie.root.subMiddlewares.get(G).push(...z);const U=E[E.length-1];this.trie.insert(G,{handler:U,method:L})}get(L,...G){return this.#E("GET",L,G)}post(L,...G){return this.#E("POST",L,G)}put(L,...G){return this.#E("PUT",L,G)}patch(L,...G){if(G.length>0)return this.#E("PATCH",L,G)}delete(L,...G){return this.#E("DELETE",L,G)}}var y=D;export{y as default};
1
+ var C=(J,L)=>()=>(L||J((L={exports:{}}).exports,L),L.exports);var y=C((R)=>{Object.defineProperty(R,"__esModule",{value:!0});class S{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class w{constructor(){this.root=new S}insert(J,L){let z=this.root;const U=J.split("/").filter(Boolean);if(J==="/"){z.isEndOfWord=!0,z.handler.push(L.handler),z.path=J,z.method.push(L.method);return}for(let Y of U){let X=!1,Z=Y;if(Y.startsWith(":"))X=!0,Z=":";if(!z.children[Z])z.children[Z]=new S;z=z.children[Z],z.isDynamic=X,z.pattern=Y}z.isEndOfWord=!0,z.method.push(L.method),z.handler.push(L.handler),z.path=J}search(J,L){let z=this.root;const U=J.split("/").filter(Boolean);for(let X of U){let Z=X;if(!z.children[Z])if(z.children[":"])z=z.children[":"];else return null;else z=z.children[Z]}let Y=z.method.indexOf(L);if(Y!==-1)return{path:z.path,handler:z.handler[Y],isDynamic:z.isDynamic,pattern:z.pattern,method:z.method[Y]};return{path:z.path,handler:z.handler,isDynamic:z.isDynamic,pattern:z.pattern,method:z.method[Y]}}}R.default=w});var P=C((b)=>{function p(J,L){let z={},U={},Y=!1,X=null,Z=null,W=null,Q,V=200;return{req:J,url:L,next:()=>{},status($){return V=$,this},body(){return O(this,void 0,void 0,function*(){if(!Q)Q=yield l(J);if(Q.error)return new Response(JSON.stringify({error:Q.error}),{status:400,headers:{"Content-Type":"application/json"}});return Q})},setHeader($,E){return z[$]=E,this},set($,E){return U[$]=E,this},get($){return U[$]||null},setAuth($){return Y=$,this},getAuth(){return Y},text($,E){if(E)V=E;return new Response($,{status:V,headers:z})},json($,E){if(E)V=E;return new Response(JSON.stringify($),{status:V,headers:Object.assign({"Content-Type":"application/json"},z)})},html($,E){if(E)V=E;return new Response(Bun.file($),{status:V,headers:Object.assign({},z)})},file($,E){if(E)V=E;return new Response(Bun.file($),{status:V,headers:Object.assign({},z)})},redirect($,E){if(E)V=E;return new Response(null,{status:V,headers:Object.assign({Location:$},z)})},getParams($){if(!W)W=n(J===null||J===void 0?void 0:J.routePattern,L===null||L===void 0?void 0:L.pathname);return $?W[$]||null:W},getQuery($){if(!X)X=Object.fromEntries(L.searchParams);return $?X[$]||null:X},cookie($,E){return O(this,arguments,void 0,function*(c,h,B={}){let K=`${encodeURIComponent(c)}=${encodeURIComponent(h)}`;if(B.maxAge)K+=`; Max-Age=${B.maxAge}`;if(B.expires)K+=`; Expires=${B.expires.toUTCString()}`;if(B.path)K+=`; Path=${B.path}`;if(B.domain)K+=`; Domain=${B.domain}`;if(B.secure)K+="; Secure";if(B.httpOnly)K+="; HttpOnly";if(B.sameSite)K+=`; SameSite=${B.sameSite}`;if(z["Set-Cookie"]){const q=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];q.push(K),z["Set-Cookie"]=q}else z["Set-Cookie"]=K;return this})},getCookie($){return O(this,void 0,void 0,function*(){if(!Z){const E=J.headers.get("cookie");if(E)Z=yield i(E)}return $?Z[$]||null:Z})}}}function i(J){return O(this,void 0,void 0,function*(){const L={};if(!J)return L;return J.split(";").forEach((U)=>{var Y;const[X,Z]=(Y=U===null||U===void 0?void 0:U.trim())===null||Y===void 0?void 0:Y.split("=");if(X&&Z)L[X.trim()]=Z.split(" ")[0].trim()}),L})}function n(J,L){const z={},U=J.split("/"),[Y]=L.split("?"),X=Y.split("/");if(U.length!==X.length)return null;return U.forEach((Z,W)=>{if(Z.startsWith(":")){const Q=Z.slice(1);z[Q]=X[W]}}),z}function l(J){return O(this,void 0,void 0,function*(){const L=J.headers.get("Content-Type")||"";if(!L)return{};try{if(L.startsWith("application/json"))return yield J.json();if(L.startsWith("application/x-www-form-urlencoded")){const z=yield J.text();return Object.fromEntries(new URLSearchParams(z))}if(L.startsWith("multipart/form-data")){const z=yield J.formData();return d(z)}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}})}function d(J){const L={};for(let[z,U]of J.entries())L[z]=U;return L}var O=b&&b.__awaiter||function(J,L,z,U){function Y(X){return X instanceof z?X:new z(function(Z){Z(X)})}return new(z||(z=Promise))(function(X,Z){function W($){try{V(U.next($))}catch(E){Z(E)}}function Q($){try{V(U.throw($))}catch(E){Z(E)}}function V($){$.done?X($.value):Y($.value).then(W,Q)}V((U=U.apply(J,L||[])).next())})};Object.defineProperty(b,"__esModule",{value:!0});b.default=p});var g=C((G)=>{function a(J,L,z){return x(this,void 0,void 0,function*(){const U=s.default(J,L);if(z.hasOnReqHook)yield z.hooks.onRequest(U);if(z.hasMiddleware){const X=[...z.globalMiddlewares,...z.middlewares.get(L.pathname)||[]],Z=yield r(X,U);if(Z)return Z}let Y;if(H[L.pathname+J.method])Y=H[L.pathname+J.method];else Y=z.trie.search(L.pathname,J.method),H[L.pathname+J.method]=Y;if(!Y||!Y.handler)return new Response(`Route not found for ${L.pathname}`,{status:404});if(Y.method!==J.method)return new Response("Method not allowed",{status:405});if(Y.isDynamic)J.routePattern=Y.path;if(z.hasPreHandlerHook){const X=yield z.hooks.preHandler(U);if(X)return X}try{const X=yield Y.handler(U);if(z.hasPostHandlerHook)yield z.hooks.postHandler(U);if(z.hasOnSendHook){const Z=yield z.hooks.onSend(X,U);if(Z)return Z}return X!==null&&X!==void 0?X:new Response("No response from handler",{status:204})}catch(X){return new Response("Internal Server Error",{status:500})}})}function r(J,L){return x(this,void 0,void 0,function*(){for(let z of J){const U=yield z(L);if(U)return U}})}var x=G&&G.__awaiter||function(J,L,z,U){function Y(X){return X instanceof z?X:new z(function(Z){Z(X)})}return new(z||(z=Promise))(function(X,Z){function W($){try{V(U.next($))}catch(E){Z(E)}}function Q($){try{V(U.throw($))}catch(E){Z(E)}}function V($){$.done?X($.value):Y($.value).then(W,Q)}V((U=U.apply(J,L||[])).next())})},o=G&&G.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(G,"__esModule",{value:!0});G.default=a;var s=o(P()),H={}});var m=C((A)=>{var t=A&&A.__awaiter||function(J,L,z,U){function Y(X){return X instanceof z?X:new z(function(Z){Z(X)})}return new(z||(z=Promise))(function(X,Z){function W($){try{V(U.next($))}catch(E){Z(E)}}function Q($){try{V(U.throw($))}catch(E){Z(E)}}function V($){$.done?X($.value):Y($.value).then(W,Q)}V((U=U.apply(J,L||[])).next())})},j=A&&A.__classPrivateFieldGet||function(J,L,z,U){if(z==="a"&&!U)throw new TypeError("Private accessor was defined without a getter");if(typeof L==="function"?J!==L||!U:!L.has(J))throw new TypeError("Cannot read private member from an object whose class did not declare it");return z==="m"?U:z==="a"?U.call(J):U?U.value:L.get(J)},v=A&&A.__importDefault||function(J){return J&&J.__esModule?J:{default:J}},F,I;Object.defineProperty(A,"__esModule",{value:!0});var f=v(y()),e=v(g());class k{constructor(){F.add(this),this.routes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new f.default,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}}addHooks(J,L){if(typeof J!=="string")throw new Error("hookName must be a string");if(typeof L!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(J))this.hooks[J]=L;else throw new Error(`Unknown hook type: ${J}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[J,L]of this.middlewares.entries())if(L.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(J,L,{sslCert:z=null,sslKey:U=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof J!=="number")throw new Error("Port must be a numeric value");this.compile();const Y={port:J,fetch:(Z)=>t(this,void 0,void 0,function*(){const W=new URL(Z.url);try{return yield e.default(Z,W,this)}catch(Q){return new Response("Internal Server Error",{status:500})}}),onClose(){console.log("Server is shutting down...")}};if(z&&U)Y.certFile=z,Y.keyFile=U;const X=Bun.serve(Y);if(typeof L==="function")return L();if(z&&U)console.log(`HTTPS server is running on https://localhost:${J}`);else console.log(`HTTP server is running on http://localhost:${J}`);return X}register(J,L){if(typeof J!=="string")throw new Error("path must be a string");if(typeof L!=="object")throw new Error("handler parameter should be a instance of router object",L);const z=Object.entries(L.trie.root.children);L.trie.root.subMiddlewares.forEach((U,Y)=>{if(!this.middlewares.has(J+Y))this.middlewares.set(J+Y,[]);U===null||U===void 0||U.forEach((X)=>{var Z,W;if(!((Z=this.middlewares.get(J+Y))===null||Z===void 0?void 0:Z.includes(X)))(W=this.middlewares.get(J+Y))===null||W===void 0||W.push(X)})});for(let[U,Y]of z){const X=J+(Y===null||Y===void 0?void 0:Y.path),Z=Y.handler[0],W=Y.method[0];this.trie.insert(X,{handler:Z,method:W})}L.trie=new f.default}use(J,L){var z,U;if(typeof J==="function"){if(!this.globalMiddlewares.includes(J))return this.globalMiddlewares.push(J)}const Y=J;if(!this.middlewares.has(Y))this.middlewares.set(Y,[]);if(!((z=this.middlewares.get(Y))===null||z===void 0?void 0:z.includes(L)))(U=this.middlewares.get(Y))===null||U===void 0||U.push(L)}get(J,...L){return j(this,F,"m",I).call(this,"GET",J,L),this}post(J,...L){return j(this,F,"m",I).call(this,"POST",J,L),this}put(J,...L){return j(this,F,"m",I).call(this,"PUT",J,L),this}patch(J,...L){return j(this,F,"m",I).call(this,"PATCH",J,L),this}delete(J,...L){return j(this,F,"m",I).call(this,"DELETE",J,L),this}}F=new WeakSet,I=function J(L,z,U){if(typeof z!=="string")throw new Error("Path must be a string type");if(typeof L!=="string")throw new Error("method must be a string type");const Y=U.slice(0,-1),X=U[U.length-1];if(!this.middlewares.has(z))this.middlewares.set(z,[]);Y.forEach((Z)=>{var W,Q;if(z==="/"){if(!this.globalMiddlewares.includes(Z))this.globalMiddlewares.push(Z)}else if(!((W=this.middlewares.get(z))===null||W===void 0?void 0:W.includes(Z)))(Q=this.middlewares.get(z))===null||Q===void 0||Q.push(Z)}),this.trie.insert(z,{handler:X,method:L})};A.default=k});var Lz=C((M)=>{var D=M&&M.__classPrivateFieldGet||function(J,L,z,U){if(z==="a"&&!U)throw new TypeError("Private accessor was defined without a getter");if(typeof L==="function"?J!==L||!U:!L.has(J))throw new TypeError("Cannot read private member from an object whose class did not declare it");return z==="m"?U:z==="a"?U.call(J):U?U.value:L.get(J)},zz=M&&M.__importDefault||function(J){return J&&J.__esModule?J:{default:J}},T,N;Object.defineProperty(M,"__esModule",{value:!0});var Jz=zz(m());class _ extends Jz.default{constructor(){super();T.add(this)}get(J,...L){return D(this,T,"m",N).call(this,"GET",J,L),this}post(J,...L){return D(this,T,"m",N).call(this,"POST",J,L),this}put(J,...L){return D(this,T,"m",N).call(this,"PUT",J,L),this}patch(J,...L){return D(this,T,"m",N).call(this,"PATCH",J,L),this}delete(J,...L){return D(this,T,"m",N).call(this,"DELETE",J,L),this}}T=new WeakSet,N=function J(L,z,U){if(!this.trie.root.subMiddlewares.has(z))this.trie.root.subMiddlewares.set(z,[]);const Y=U.slice(0,-1),X=this.trie.root.subMiddlewares.get(z);Y.forEach((W)=>{if(!(X===null||X===void 0?void 0:X.includes(W)))X===null||X===void 0||X.push(W)});const Z=U[U.length-1];this.trie.insert(z,{handler:Z,method:L})};M.default=_});export default Lz();
package/dist/trie.js CHANGED
@@ -1 +1 @@
1
- class E{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class F{constructor(){this.root=new E}insert(j,z){let b=this.root;const C=j.split("/").filter(Boolean);if(j==="/"){b.isEndOfWord=!0,b.handler.push(z.handler),b.path=j,b.method.push(z.method);return}for(let q of C){let B=!1,A=q;if(q.startsWith(":"))B=!0,A=":";if(!b.children[A])b.children[A]=new E;b=b.children[A],b.isDynamic=B,b.pattern=q}b.isEndOfWord=!0,b.method.push(z.method),b.handler.push(z.handler),b.path=j}insertMidl(j){if(!this.root.subMiddlewares.has(j))this.root.subMiddlewares.set(j)}search(j,z){let b=this.root;const C=j.split("/").filter(Boolean);for(let B of C){let A=B;if(!b.children[A])if(b.children[":"])b=b.children[":"];else return null;else b=b.children[A]}let q=b.method.indexOf(z);if(q!==-1)return{path:b.path,handler:b.handler[q],isDynamic:b.isDynamic,pattern:b.pattern,method:b.method[q]};return{path:b.path,handler:b.handler,isDynamic:b.isDynamic,pattern:b.pattern,method:b.method[q]}}getAllRoutes(){const j=[],z=(b,C)=>{if(b.isEndOfWord)j.push({path:C,handler:b.handler,isImportant:b.isImportant,isDynamic:b.isDynamic,pattern:b.pattern});for(let q in b.children){const B=b.children[q],A=C+(q===":"?"/:"+B.pattern:"/"+q);z(B,A)}};return z(this.root,""),j}}export{F as default};
1
+ var H=(v,q)=>()=>(q||v((q={exports:{}}).exports,q),q.exports);var K=H((G)=>{Object.defineProperty(G,"__esModule",{value:!0});class C{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class E{constructor(){this.root=new C}insert(v,q){let j=this.root;const B=v.split("/").filter(Boolean);if(v==="/"){j.isEndOfWord=!0,j.handler.push(q.handler),j.path=v,j.method.push(q.method);return}for(let w of B){let A=!1,z=w;if(w.startsWith(":"))A=!0,z=":";if(!j.children[z])j.children[z]=new C;j=j.children[z],j.isDynamic=A,j.pattern=w}j.isEndOfWord=!0,j.method.push(q.method),j.handler.push(q.handler),j.path=v}search(v,q){let j=this.root;const B=v.split("/").filter(Boolean);for(let A of B){let z=A;if(!j.children[z])if(j.children[":"])j=j.children[":"];else return null;else j=j.children[z]}let w=j.method.indexOf(q);if(w!==-1)return{path:j.path,handler:j.handler[w],isDynamic:j.isDynamic,pattern:j.pattern,method:j.method[w]};return{path:j.path,handler:j.handler,isDynamic:j.isDynamic,pattern:j.pattern,method:j.method[w]}}}G.default=E});export default K();
Binary file
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
7
+ <title>HTML 5 Boilerplate</title>
8
+ <link rel="stylesheet" href="style.css" />
9
+ </head>
10
+ <body>
11
+ Hello world!
12
+ </body>
13
+ </html>
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "test",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "scripts": {
6
+ "test": "echo \"Error: no test specified\" && exit 1"
7
+ },
8
+ "keywords": [],
9
+ "author": "",
10
+ "license": "ISC",
11
+ "description": "",
12
+ "dependencies": {
13
+ "jsonwebtoken": "^9.0.2"
14
+ }
15
+ }
@@ -0,0 +1,21 @@
1
+ import Router from "../src/router";
2
+
3
+ const route = new Router();
4
+
5
+ const h = () => {
6
+ console.log('object');
7
+ }
8
+
9
+ const s = () =>{
10
+ console.log('s')
11
+ }
12
+
13
+ route.get("/register", h,(xl) => {
14
+ return xl.text("from register user");
15
+ })
16
+
17
+ route.get("/login",h,s,(xl)=>{
18
+ return new Response("hello loin")
19
+ })
20
+
21
+ export default route;
@@ -0,0 +1,27 @@
1
+ import http from 'k6/http';
2
+ import { check } from 'k6';
3
+
4
+ // Define the test options
5
+ export let options = {
6
+ stages: [
7
+ { duration: '30s', target: 500 }, // Ramp up to 500 users in 30 seconds
8
+ { duration: '30s', target: 1000 }, // Ramp up to 1,000 users in the next 30 seconds
9
+ { duration: '30s', target: 1500 }, // Ramp up to 2,000 users in the following 30 seconds
10
+ { duration: '1m', target: 1000 }, // Hold at 2,000 users for 1 minute
11
+ { duration: '30s', target: 0 }, // Gradually scale down to 0 users
12
+ ],
13
+ thresholds: {
14
+ http_req_duration: ['p(95)<500'], // 95% of requests should complete in under 500ms
15
+ http_req_failed: ['rate<0.01'], // Less than 1% of requests should fail
16
+ },
17
+ };
18
+
19
+ export default function () {
20
+ // Make a GET request to your API endpoint
21
+ let res = http.get('http://localhost:3000/');
22
+
23
+ // Check if the response status is 200
24
+ check(res, {
25
+ 'status is 200': (r) => r.status === 200,
26
+ });
27
+ }
@@ -0,0 +1,85 @@
1
+ import Diesel from "../src/main";
2
+ import jwt from "jsonwebtoken";
3
+
4
+ const app = new Diesel();
5
+ const secret = "secret";
6
+
7
+ app.get("/r", (xl) => {
8
+ return xl.html(`${import.meta.dir}/index.html`);
9
+ });
10
+
11
+ // app.use((xl) => {
12
+ // const cok = xl.getCookie('accessToken');
13
+
14
+ // if (cok) {
15
+ // try {
16
+ // const vcok = jwt.verify(cok, secret);
17
+ // xl.setAuth(true);
18
+ // xl.set('user',vcok)
19
+ // } catch (error) {
20
+ // // console.log('Token verification failed:', error);
21
+ // xl.setAuth(false);
22
+ // }
23
+ // } else {
24
+ // xl.setAuth(false);
25
+ // }
26
+
27
+ // return null;
28
+ // });
29
+
30
+ // app.use(h)
31
+ // Main route handler for "/"
32
+
33
+ // app.addHooks('onRequest',(xl)=>{
34
+ // console.log('on req hooks');
35
+ // })
36
+
37
+
38
+ app.get("/", async (xl) => {
39
+ return new Response("hello world")
40
+ })
41
+
42
+ app.post("/", async (xl) => {
43
+ const body = await xl.body();
44
+ return new Response(JSON.stringify(body)); // This will log the parsed body content
45
+ });
46
+
47
+ app.get("/c", async(xl) => {
48
+ const user = {
49
+ name: "pk",
50
+ age: 22,
51
+ };
52
+
53
+ const accessToken = jwt.sign(user, secret, { expiresIn: "1d" });
54
+ const refreshToken = jwt.sign(user, secret, { expiresIn: "10d" });
55
+ const options = {
56
+ httpOnly: true, // Makes cookie accessible only by the web server (not JS)
57
+ secure: true, // Ensures the cookie is sent over HTTPS
58
+ maxAge: 24 * 60 * 60 * 1000, // 1 day in milliseconds
59
+ sameSite: "Strict", // Prevents CSRF (strict origin policy)
60
+ path: "/", // Cookie available for all routes
61
+ };
62
+ await xl.cookie("accessToken", accessToken, options)
63
+ await xl.cookie("refreshToken", refreshToken, options)
64
+ // xl.cookie("refreshToken", refreshToken, options);
65
+ await xl.getCookie()
66
+ return xl.status(200).json({msg:"setting cookies"})
67
+ });
68
+
69
+ // For "/test", middlewares h, s will run before the handler
70
+ app.get("/test/:id", async (xl) => {
71
+ const q = xl.getQuery();
72
+ const params = xl.getParams('id');
73
+ return new Response(JSON.stringify({ msg: "hello world", q, params }));
74
+ });
75
+
76
+ // For "/ok", only middleware h will run before the handler
77
+ app.get("/redirect", (xl) => {
78
+ return xl.redirect("/");
79
+ });
80
+
81
+ import userRoute from "./route.js";
82
+
83
+ app.register("/api/user", userRoute);
84
+
85
+ app.listen(3000);
package/jsconfig.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Enable latest features
4
+ "lib": ["ESNext", "DOM"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+ "outDir":"dist",
11
+
12
+ // Bundler mode
13
+ "moduleResolution": "bundler",
14
+ "allowImportingTsExtensions": true,
15
+ "verbatimModuleSyntax": true,
16
+ "noEmit": true,
17
+
18
+ // Best practices
19
+ "strict": true,
20
+ "skipLibCheck": true,
21
+ "noFallthroughCasesInSwitch": true,
22
+
23
+ // Some stricter flags (disabled by default)
24
+ "noUnusedLocals": false,
25
+ "noUnusedParameters": false,
26
+ "noPropertyAccessFromIndexSignature": false
27
+ }
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "main": "dist/server.js",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -8,5 +8,11 @@
8
8
  "keywords": [],
9
9
  "author": "",
10
10
  "license": "ISC",
11
- "description": ""
12
- }
11
+ "description": "",
12
+ "devDependencies": {
13
+ "@types/bun": "latest"
14
+ },
15
+ "peerDependencies": {
16
+ "typescript": "^5.0.0"
17
+ }
18
+ }
package/src/ctx.ts ADDED
@@ -0,0 +1,215 @@
1
+ import type { ContextType, CookieOptions, ParseBodyResult } from "./types";
2
+
3
+ export default function createCtx(req: Request, url: URL): ContextType {
4
+ let headers : Headers = new Headers()
5
+ let settedValue: Record<string, string> = {};
6
+ let isAuthenticated = false;
7
+ let parsedQuery: any = null;
8
+ let parsedCookie: any = null
9
+ let parsedParams: any = null;
10
+ let parsedBody: ParseBodyResult | null;
11
+ let responseStatus = 200;
12
+
13
+ return {
14
+ req,
15
+ url,
16
+ next: () => { },
17
+
18
+ // Set response status for chaining
19
+ status(status: number) {
20
+ responseStatus = status;
21
+ return this;
22
+ },
23
+
24
+ async body(): Promise<any> {
25
+ if (!parsedBody) {
26
+ parsedBody = await parseBody(req);
27
+ }
28
+ if (parsedBody.error) {
29
+ return new Response(JSON.stringify({ error: parsedBody.error }), {
30
+ status: 400, // Bad Request
31
+ });
32
+ }
33
+ return parsedBody;
34
+ },
35
+
36
+ setHeader(key: string, value: any) {
37
+ headers.set(key,value)
38
+ return this;
39
+ },
40
+
41
+ set(key: string, value: any) {
42
+ settedValue[key] = value;
43
+ return this;
44
+ },
45
+
46
+ get(key: string) {
47
+ return settedValue[key] || null;
48
+ },
49
+
50
+ setAuth(authStatus: boolean) {
51
+ isAuthenticated = authStatus;
52
+ return this;
53
+ },
54
+
55
+ getAuth() {
56
+ return isAuthenticated;
57
+ },
58
+
59
+ // Response methods with optional status
60
+ text(data: string, status?: number) {
61
+ return new Response(data, {
62
+ status: status ?? responseStatus,
63
+ headers
64
+ });
65
+ },
66
+
67
+ json(data: any, status?: number) {
68
+ return new Response(JSON.stringify(data), {
69
+ status: status ?? responseStatus,
70
+ headers
71
+ });
72
+ },
73
+
74
+ html(filepath: string, status?: number) {
75
+ return new Response(Bun.file(filepath), {
76
+ status: status ?? responseStatus,
77
+ headers
78
+ });
79
+ },
80
+
81
+ file(filePath: string, status?: number) {
82
+ return new Response(Bun.file(filePath), {
83
+ status: status ?? responseStatus,
84
+ headers
85
+ });
86
+ },
87
+
88
+ redirect(path: string, status?: number) {
89
+ headers.set('Location', path);
90
+ return new Response(null, {
91
+ status: status ?? 302,
92
+ headers
93
+ });
94
+ },
95
+
96
+ getParams(props: string)
97
+ : string | Record<string, string> | null {
98
+ if (!parsedParams) {
99
+ parsedParams = extractDynamicParams(req?.routePattern, url?.pathname);
100
+ }
101
+ return props ? parsedParams[props] || null : parsedParams;
102
+ },
103
+
104
+ getQuery(props?: any)
105
+ : string | Record<string, string> | null {
106
+ if (!parsedQuery) {
107
+ parsedQuery = Object.fromEntries(url.searchParams);
108
+ }
109
+ return props ? parsedQuery[props] || null : parsedQuery;
110
+ },
111
+
112
+ async cookie(name: string, value: string, options: CookieOptions = {}) {
113
+ let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
114
+
115
+ // Add options to cookie string (e.g., expiration, path, HttpOnly, etc.)
116
+ if (options.maxAge) cookieString += `; Max-Age=${options.maxAge}`;
117
+ if (options.expires) cookieString += `; Expires=${options.expires.toUTCString()}`;
118
+ if (options.path) cookieString += `; Path=${options.path}`;
119
+ if (options.domain) cookieString += `; Domain=${options.domain}`;
120
+ if (options.secure) cookieString += `; Secure`;
121
+ if (options.httpOnly) cookieString += `; HttpOnly`;
122
+ if (options.sameSite) cookieString += `; SameSite=${options.sameSite}`;
123
+
124
+ headers?.append('Set-Cookie',cookieString)
125
+ // console.log(headers)
126
+ // console.log(Object.fromEntries(headers))
127
+
128
+ return this;
129
+ },
130
+
131
+ async getCookie(cookieName?: string)
132
+ : Promise<string | Record<string, string> | null> {
133
+ if (!parsedCookie) {
134
+ const cookieHeader = req.headers.get("cookie")
135
+ if (cookieHeader) {
136
+ parsedCookie = await parseCookie(cookieHeader);
137
+ }
138
+ }
139
+ return cookieName ? parsedCookie[cookieName] || null : parsedCookie;
140
+ },
141
+ };
142
+ }
143
+
144
+
145
+ async function parseCookie(header: string | undefined)
146
+ : Promise<Record<string, string>> {
147
+ const cookies: Record<string, string> = {};
148
+ if (!header) return cookies;
149
+
150
+ const cookieArray = header.split(";");
151
+ cookieArray.forEach((cookie) => {
152
+ const [cookieName, cookieValue] = cookie?.trim()?.split("=");
153
+ if (cookieName && cookieValue) {
154
+ cookies[cookieName.trim()] = cookieValue.split(' ')[0].trim()
155
+ }
156
+ });
157
+ return cookies;
158
+ }
159
+
160
+ function extractDynamicParams(routePattern: any, path: string)
161
+ : Record<string, string> | null {
162
+ const object: Record<string, string> = {};
163
+ const routeSegments = routePattern.split("/");
164
+ const [pathWithoutQuery] = path.split("?");
165
+ const pathSegments = pathWithoutQuery.split("/");
166
+
167
+ if (routeSegments.length !== pathSegments.length) {
168
+ return null;
169
+ }
170
+
171
+ routeSegments.forEach((segment: string, index: number) => {
172
+ if (segment.startsWith(":")) {
173
+ const dynamicKey = segment.slice(1);
174
+ object[dynamicKey] = pathSegments[index];
175
+ }
176
+ });
177
+
178
+ return object;
179
+ }
180
+
181
+ async function parseBody(req: Request)
182
+ : Promise<ParseBodyResult> {
183
+ const contentType: string = req.headers.get("Content-Type") || "";
184
+
185
+ if (!contentType) return {};
186
+
187
+ try {
188
+ if (contentType.startsWith("application/json")) {
189
+ return await req.json();
190
+ }
191
+
192
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
193
+ const body = await req.text();
194
+ return Object.fromEntries(new URLSearchParams(body));
195
+ }
196
+
197
+ if (contentType.startsWith("multipart/form-data")) {
198
+ const formData = await req.formData();
199
+ return formDataToObject(formData);
200
+ }
201
+
202
+ return { error: "Unknown request body type" };
203
+ } catch (error) {
204
+ return { error: "Invalid request body format" };
205
+ }
206
+ }
207
+
208
+
209
+ function formDataToObject(formData: any): Record<string, string> {
210
+ const obj: Record<string, string> = {};
211
+ for (const [key, value] of formData.entries()) {
212
+ obj[key] = value;
213
+ }
214
+ return obj;
215
+ }