diesel-core 1.2.1 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ctx.js +1 -1
- package/dist/handleRequest.js +1 -1
- package/dist/main.js +3 -3
- package/dist/middlewares/cors/index.test.d.ts +1 -0
- package/dist/middlewares/filesave/index.test.d.ts +1 -0
- package/dist/middlewares/filesave/savefile.js +1 -1
- package/dist/middlewares/jwt/index.js +1 -1
- package/dist/middlewares/jwt/index.test.d.ts +1 -0
- package/dist/middlewares/logger/logger.js +3 -3
- package/dist/middlewares/powered-by/index.test.d.ts +1 -0
- package/dist/middlewares/ratelimit/index.test.d.ts +1 -0
- package/dist/types.d.ts +1 -1
- package/dist/utils/jwt.js +1 -1
- package/package.json +8 -8
- package/dist/routes/hello.d.ts +0 -1
- package/dist/routes/user/api.d.ts +0 -1
package/dist/ctx.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.create;var{getPrototypeOf:I,defineProperty:X,getOwnPropertyNames:M}=Object;var N=Object.prototype.hasOwnProperty;var R=(w,A,E)=>{E=w!=null?j(I(w)):{};let z=A||!w||!w.__esModule?X(E,"default",{value:w,enumerable:!0}):E;for(let F of M(w))if(!N.call(z,F))X(z,F,{get:()=>w[F],enumerable:!0});return z};var U=((w)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(w,{get:(A,E)=>(typeof require!=="undefined"?require:A)[E]}):w)(function(w){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+w+'" is not supported')});function Y(w){switch(w.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function V(w,A,E){let z=null,F=null,J=null,G=null,O={};return{req:w,server:A,url:E,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,
|
|
1
|
+
var j=Object.create;var{getPrototypeOf:I,defineProperty:X,getOwnPropertyNames:M}=Object;var N=Object.prototype.hasOwnProperty;var R=(w,A,E)=>{E=w!=null?j(I(w)):{};let z=A||!w||!w.__esModule?X(E,"default",{value:w,enumerable:!0}):E;for(let F of M(w))if(!N.call(z,F))X(z,F,{get:()=>w[F],enumerable:!0});return z};var U=((w)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(w,{get:(A,E)=>(typeof require!=="undefined"?require:A)[E]}):w)(function(w){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+w+'" is not supported')});function Y(w){switch(w.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function V(w,A,E){let z=null,F=null,J=null,G=null,O={};return{req:w,server:A,url:E,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,g){return this.headers.set(f,g),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return z},get params(){if(!F&&this.req.routePattern)try{F=_(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return F??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!G)G=(async()=>{let f=await B(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return G},set(f,g){return O[f]=g,this},get(f){return O[f]},text(f,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,g){if(g)this.status=g;let L=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),x;if(f instanceof Uint8Array)x="Uint8Array";else if(f instanceof ArrayBuffer)x="ArrayBuffer";else x=typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",L.get(x)??"text/plain; charset=utf-8");let K=x==="object"&&f!==null?JSON.stringify(f):f;return new Response(K,{status:this.status,headers:this.headers})},json(f,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,g,L){if(L)this.status=L;let x=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",g??Y(f));return new Response(x,{status:this.status,headers:this.headers})},async ejs(f,g={},L){if(L)this.status=L;let x;try{x=await import("ejs"),x=x.default||x}catch(K){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let K=await Bun.file(f).text(),Z=x.render(K,g),$=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(Z,{status:this.status,headers:$})}catch(K){return console.error("EJS Rendering Error:",K),new Response("Error rendering template",{status:500})}},redirect(f,g){if(g)this.status=g;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let g=new Headers(this.headers),L=new ReadableStream({async start(x){await f(x),x.close()}});return new Response(L,{headers:g})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,g,L={}){let x=`${encodeURIComponent(f)}=${encodeURIComponent(g)}`;if(L.maxAge)x+=`; Max-Age=${L.maxAge}`;if(L.expires)x+=`; Expires=${L.expires.toUTCString()}`;if(L.path)x+=`; Path=${L.path}`;if(L.domain)x+=`; Domain=${L.domain}`;if(L.secure)x+="; Secure";if(L.httpOnly)x+="; HttpOnly";if(L.sameSite)x+=`; SameSite=${L.sameSite}`;return this.headers.append("Set-Cookie",x),this},get cookies(){if(!J){let f=this.req.headers.get("cookie");J=f?W(f):{}}return J}}}function W(w){return Object.fromEntries(w.split(";").map((A)=>{let[E,...z]=A.trim().split("=");return[E,decodeURIComponent(z.join("="))]}))}function _(w,A){let E={},z=w.split("/"),[F]=A.split("?"),J=F.split("/");if(z.length!==J.length)return null;for(let G=0;G<z.length;G++)if(z[G].startsWith(":"))E[z[G].slice(1)]=J[G];return E}async function B(w){let A=w.headers.get("Content-Type");if(!A)return{};if(w.headers.get("Content-Length")==="0"||!w.body)return{};try{if(A.startsWith("application/json"))return await w.json();if(A.startsWith("application/x-www-form-urlencoded")){let z=await w.text();return Object.fromEntries(new URLSearchParams(z))}if(A.startsWith("multipart/form-data")){let z=await w.formData(),F={};for(let[J,G]of z.entries())F[J]=G;return F}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}export{V as default};
|
package/dist/handleRequest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var D=Object.create;var{getPrototypeOf:C,defineProperty:_,getOwnPropertyNames:E}=Object;var F=Object.prototype.hasOwnProperty;var g=(A,K,X)=>{X=A!=null?D(C(A)):{};let z=K||!A||!A.__esModule?_(X,"default",{value:A,enumerable:!0}):X;for(let O of E(A))if(!F.call(z,O))_(z,O,{get:()=>A[O],enumerable:!0});return z};var M=((A)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(A,{get:(K,X)=>(typeof require!=="undefined"?require:K)[X]}):A)(function(A){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});function U(A){switch(A.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function W(A,K,X){let z=null,O=null,Z=null,$=null,j={};return{req:A,server:K,url:X,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(L,G){return this.headers.set(L,G),this},removeHeader(L){return this.headers.delete(L),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(L){throw new Error("Failed to parse query parameters")}return z},get params(){if(!O&&this.req.routePattern)try{O=w(this.req.routePattern,this.url.pathname)}catch(L){throw new Error("Failed to extract route parameters")}return O??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!$)$=(async()=>{let L=await T(this.req);if(L.error)throw new Error(L.error);return Object.keys(L).length===0?null:L})();return $},set(L,G){return j[L]=G,this},get(L){return j[L]},text(L,G){if(G)this.status=G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(L,{status:this.status,headers:this.headers})},send(L,G){if(G)this.status=G;let J=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),Y;if(L instanceof Uint8Array)Y="Uint8Array";else if(L instanceof ArrayBuffer)Y="ArrayBuffer";else Y=typeof L;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",J.get(Y)??"text/plain; charset=utf-8");let I=Y==="object"&&L!==null?JSON.stringify(L):L;return new Response(I,{status:this.status,headers:this.headers})},json(L,G){if(G)this.status=G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(L,{status:this.status,headers:this.headers})},file(L,G,J){if(J)this.status=J;let Y=Bun.file(L);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",G??U(L));return new Response(Y,{status:this.status,headers:this.headers})},async ejs(L,G={},J){if(J)this.status=J;let Y;try{Y=await import("ejs"),Y=Y.default||Y}catch(I){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let I=await Bun.file(L).text(),N=Y.render(I,G),Q=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(N,{status:this.status,headers:Q})}catch(I){return console.error("EJS Rendering Error:",I),new Response("Error rendering template",{status:500})}},redirect(L,G){if(G)this.status=G;else this.status=302;return this.headers.set("Location",L),new Response(null,{status:this.status,headers:this.headers})},stream(L){let G=new Headers(this.headers),J=new ReadableStream({async start(Y){await L(Y),Y.close()}});return new Response(J,{headers:G})},yieldStream(L){return new Response({async*[Symbol.asyncIterator](){yield*L()}},{headers:this.headers})},setCookie(L,G,J={}){let Y=`${encodeURIComponent(L)}=${encodeURIComponent(G)}`;if(J.maxAge)Y+=`; Max-Age=${J.maxAge}`;if(J.expires)Y+=`; Expires=${J.expires.toUTCString()}`;if(J.path)Y+=`; Path=${J.path}`;if(J.domain)Y+=`; Domain=${J.domain}`;if(J.secure)Y+="; Secure";if(J.httpOnly)Y+="; HttpOnly";if(J.sameSite)Y+=`; SameSite=${J.sameSite}`;return this.headers.append("Set-Cookie",Y),this},get cookies(){if(!Z){let L=this.req.headers.get("cookie");Z=L?b(L):{}}return Z}}}function b(A){return Object.fromEntries(A.split(";").map((K)=>{let[X,...z]=K.trim().split("=");return[X,decodeURIComponent(z.join("="))]}))}function w(A,K){let X={},z=A.split("/"),[O]=K.split("?"),Z=O.split("/");if(z.length!==Z.length)return null;for(let $=0;$<z.length;$++)if(z[$].startsWith(":"))X[z[$].slice(1)]=Z[$];return X}async function T(A){let K=A.headers.get("Content-Type");if(!K)return{};if(A.headers.get("Content-Length")==="0"||!A.body)return{};try{if(K.startsWith("application/json"))return await A.json();if(K.startsWith("application/x-www-form-urlencoded")){let z=await A.text();return Object.fromEntries(new URLSearchParams(z))}if(K.startsWith("multipart/form-data")){let z=await A.formData(),O={};for(let[Z,$]of z.entries())O[Z]=$;return O}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}async function P(A,K,X,z){let O=W(A,K,X),Z=z.trie.search(X.pathname,A.method);A.routePattern=Z?.path;try{if(z.hasFilterEnabled){let L=A.routePattern??X.pathname,G=await x(z,L,O,K),J=G instanceof Promise?await G:G;if(J)return J}if(z.hasMiddleware){if(z.globalMiddlewares.length){let G=await B(z.globalMiddlewares,O,K);if(G)return G}let L=z.middlewares.get(X.pathname)||[];if(L?.length){let G=await B(L,O,K);if(G)return G}}if(!Z?.handler||Z.method!==A.method){if(z.staticPath){let L=await f(z,X.pathname,O);if(L)return L;let G=z.trie.search("*",A.method);if(G?.handler)return await G.handler(O)}if(z.hooks.routeNotFound&&Array.isArray(z.hooks.routeNotFound)&&!Z?.handler){let L=z.hooks.routeNotFound;for(let G=0;G<L.length;G++){let J=L[G](O),Y=J instanceof Promise?await J:J;if(Y)return Y}}if(!Z||!Z?.handler?.length)return V(404,`Route not found for ${X.pathname}`);if(Z?.method!==A.method)return V(405,"Method not allowed")}if(z.hooks.preHandler?.length&&Array.isArray(z.hooks.preHandler)){let L=z.hooks.preHandler;for(let G=0;G<L.length;G++){let J=L[G](O),Y=J instanceof Promise?await J:J;if(Y)return Y}}let $=Z.handler(O);return($ instanceof Promise?await $:$)??V(204,"")}catch($){if(z.hooks.onError&&Array.isArray(z.hooks.onError)){let j=z.hooks.onError;for(let L=0;L<j.length;L++){let G=z.hooks.onError[L]($,A,X,K),J=G instanceof Promise?await G:G;if(J)return J}}return V(500,"Internal Server Error")}finally{if(z.hooks.onSend&&Array.isArray(z.hooks.onSend)){let $=z.hooks.onSend;for(let j=0;j<$.length;j++){let L=$[j](O),G=L instanceof Promise?await L:L;if(G)return G}}}}async function B(A,K,X){for(let z of A){let O=await z(K,X);if(O)return O}return null}async function k(A,K,X){for(let z of A){let O=await z(K,X);if(O)return O}}async function x(A,K,X,z){if(!A.filters.has(K))if(A.filterFunction.length)for(let O of A.filterFunction){let Z=await O(X,z);if(Z)return Z}else return Response.json({error:!0,message:"Protected route, authentication required",status:401},{status:401})}async function h(A,K,X,z){if(!A.filters.has(K))if(A.filterFunction.length)for(let O of A.filterFunction){let Z=await O(X,z);if(Z)return Z}else return Response.json({error:!0,message:"Protected route, authentication required",status:401},{status:401})}function V(A,K){return new Response(JSON.stringify({error:!0,message:K,status:A}),{status:A,headers:{"Content-Type":"application/json"}})}async function f(A,K,X){if(!A.staticPath)return null;let z=`${A.staticPath}${K}`;if(await Bun.file(z).exists()){let Z=U(z);return X.file(z,Z,200)}return null}export{f as handleStaticFiles,x as handleFilterRequest,h as handleBunFilterRequest,V as generateErrorResponse,B as executeMiddlewares,k as executeBunMiddlewares,P as default};
|
package/dist/main.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var l=Object.create;var{getPrototypeOf:q,defineProperty:X,getOwnPropertyNames:P}=Object;var k=Object.prototype.hasOwnProperty;var p=(n,i,t)=>{t=n!=null?l(q(n)):{};let f=i||!n||!n.__esModule?X(t,"default",{value:n,enumerable:!0}):t;for(let s of P(n))if(!k.call(f,s))X(f,s,{get:()=>n[s],enumerable:!0});return f};var h=((n)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(n,{get:(i,t)=>(typeof require!=="undefined"?require:i)[t]}):n)(function(n){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class z{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class N{root;constructor(){this.root=new z}insert(n,i){let t=this.root,f=n.split("/").filter(Boolean);if(n==="/"){t.isEndOfWord=!0,t.handler.push(i.handler),t.path=n,t.method.push(i.method);return}for(let s of f){let c=!1,o=s;if(s.startsWith(":"))c=!0,o=":";if(!t.children[o])t.children[o]=new z;t=t.children[o],t.isDynamic=c,t.pattern=s}t.isEndOfWord=!0,t.path=n,t.method.push(i.method),t.handler.push(i.handler)}search(n,i){let t=this.root,f=n.split("/").filter(Boolean),s=f.length;for(let u of f){let r=u;if(!t.children[r])if(t.children[":"])t=t.children[":"];else return null;else t=t.children[r]}let c=t.path.split("/").filter(Boolean);if(s!==c.length)return null;let o=t.method.indexOf(i);if(o!==-1)return{path:t.path,handler:t.handler[o],isDynamic:t.isDynamic,pattern:t.pattern,method:t.method[o]};return{path:t.path,handler:t.handler,isDynamic:t.isDynamic,pattern:t.pattern,method:t.method[o]}}}function T(n){switch(n.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function D(n,i,t){let f=null,s=null,c=null,o=null,u={};return{req:n,server:i,url:t,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(r,g){return this.headers.set(r,g),this},removeHeader(r){return this.headers.delete(r),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!f)try{f=Object.fromEntries(this.url.searchParams)}catch(r){throw new Error("Failed to parse query parameters")}return f},get params(){if(!s&&this.req.routePattern)try{s=a(this.req.routePattern,this.url.pathname)}catch(r){throw new Error("Failed to extract route parameters")}return s??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!o)o=(async()=>{let r=await nn(this.req);if(r.error)throw new Error(r.error);return Object.keys(r).length===0?null:r})();return o},set(r,g){return u[r]=g,this},get(r){return u[r]},text(r,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(r,{status:this.status,headers:this.headers})},send(r,g){if(g)this.status=g;let e=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),m=r instanceof Uint8Array?"Uint8Array":r instanceof ArrayBuffer?"ArrayBuffer":typeof r;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",e.get(m)??"text/plain; charset=utf-8");let C=m==="object"&&r!==null?JSON.stringify(r):r;return new Response(C,{status:this.status,headers:this.headers})},json(r,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(r,{status:this.status,headers:this.headers})},file(r,g,e){if(e)this.status=e;let m=Bun.file(r);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",g??T(r));return new Response(m,{status:this.status,headers:this.headers})},async ejs(r,g={},e){if(e)this.status=e;let m;try{m=await import("ejs"),m=m.default||m}catch(C){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let C=await Bun.file(r).text(),v=m.render(C,g),$=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(v,{status:this.status,headers:$})}catch(C){return console.error("EJS Rendering Error:",C),new Response("Error rendering template",{status:500})}},redirect(r,g){if(g)this.status=g;else this.status=302;return this.headers.set("Location",r),new Response(null,{status:this.status,headers:this.headers})},stream(r){let g=new Headers(this.headers),e=new ReadableStream({async start(m){await r(m),m.close()}});return new Response(e,{headers:g})},yieldStream(r){return new Response({async*[Symbol.asyncIterator](){yield*r()}},{headers:this.headers})},setCookie(r,g,e={}){let m=`${encodeURIComponent(r)}=${encodeURIComponent(g)}`;if(e.maxAge)m+=`; Max-Age=${e.maxAge}`;if(e.expires)m+=`; Expires=${e.expires.toUTCString()}`;if(e.path)m+=`; Path=${e.path}`;if(e.domain)m+=`; Domain=${e.domain}`;if(e.secure)m+="; Secure";if(e.httpOnly)m+="; HttpOnly";if(e.sameSite)m+=`; SameSite=${e.sameSite}`;return this.headers.append("Set-Cookie",m),this},get cookies(){if(!c){let r=this.req.headers.get("cookie");c=r?d(r):{}}return c}}}function d(n){return Object.fromEntries(n.split(";").map((i)=>{let[t,...f]=i.trim().split("=");return[t,decodeURIComponent(f.join("="))]}))}function a(n,i){let t={},f=n.split("/"),[s]=i.split("?"),c=s.split("/");if(f.length!==c.length)return null;for(let o=0;o<f.length;o++)if(f[o].startsWith(":"))t[f[o].slice(1)]=c[o];return t}async function nn(n){let i=n.headers.get("Content-Type");if(!i)return{};if(n.headers.get("Content-Length")==="0"||!n.body)return{};try{if(i.startsWith("application/json"))return await n.json();if(i.startsWith("application/x-www-form-urlencoded")){let f=await n.text();return Object.fromEntries(new URLSearchParams(f))}if(i.startsWith("multipart/form-data")){let f=await n.formData(),s={};for(let[c,o]of f.entries())s[c]=o;return s}return{error:"Unknown request body type"}}catch(f){return{error:"Invalid request body format"}}}async function U(n,i,t,f){let s=D(n,i,t),c=f.trie.search(t.pathname,n.method);n.routePattern=c?.path;try{if(t.pathname.startsWith("/favicon"))return s.text("");if(f.hasFilterEnabled){let r=n.routePattern??t.pathname,g=await on(f,r,s,i);if(g)return g}if(f.hasMiddleware){if(f.globalMiddlewares.length){let g=await Y(f.globalMiddlewares,s,i);if(g)return g}let r=f.middlewares.get(t.pathname)||[];if(r?.length){let g=await Y(r,s,i);if(g)return g}}if(!c?.handler||c.method!==n.method){if(f.staticPath){let r=await rn(f,t.pathname,s);if(r)return r;let g=f.trie.search("*",n.method);if(g?.handler)return await g.handler(s)}if(f.hooks.routeNotFound&&Array.isArray(f.hooks.routeNotFound)&&!c?.handler){let r=f.hooks.routeNotFound;for(let g=0;g<r.length;g++){let e=await r[g](s);if(e)return e}}if(!c||!c?.handler?.length)return w(404,`Route not found for ${t.pathname}`);if(c?.method!==n.method)return w(405,"Method not allowed")}if(f.hooks.preHandler?.length&&Array.isArray(f.hooks.preHandler)){let r=f.hooks.preHandler;for(let g=0;g<r.length;g++){let e=await r[g](s);if(e)return e}}let o=c.handler(s);return(o instanceof Promise?await o:o)??w(204,"")}catch(o){if(f.hooks.onError&&Array.isArray(f.hooks.onError)){let u=f.hooks.onError;for(let r=0;r<u.length;r++){let g=f.hooks.onError[r](o,n,t,i);if(g)return g}}return w(500,"Internal Server Error")}finally{if(f.hooks.onSend&&Array.isArray(f.hooks.onSend)){let o=f.hooks.onSend;for(let u=0;u<o.length;u++){let r=await o[u](s);if(r)return r}}}}async function Y(n,i,t){for(let f of n){let s=await f(i,t);if(s)return s}return null}async function b(n,i,t){for(let f of n){let s=await f(i,t);if(s)return s}}async function on(n,i,t,f){if(!n.filters.has(i))if(n.filterFunction.length)for(let s of n.filterFunction){let c=await s(t,f);if(c)return c}else return Response.json({error:!0,message:"Protected route, authentication required",status:401},{status:401})}async function xn(n,i,t,f){if(!n.filters.has(i))if(n.filterFunction.length)for(let s of n.filterFunction){let c=await s(t,f);if(c)return c}else return Response.json({error:!0,message:"Protected route, authentication required",status:401},{status:401})}function w(n,i){return new Response(JSON.stringify({error:!0,message:i,status:n}),{status:n,headers:{"Content-Type":"application/json"}})}async function rn(n,i,t){if(!n.staticPath)return null;let f=`${n.staticPath}${i}`;if(await Bun.file(f).exists()){let c=T(f);return t.file(f,c,200)}return null}var{create:tn,defineProperty:W,getOwnPropertyDescriptor:fn,getOwnPropertyNames:un,getPrototypeOf:gn}=Object,sn=Object.prototype.hasOwnProperty,cn=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports),mn=(n,i,t,f)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of un(i))!sn.call(n,s)&&s!==t&&W(n,s,{get:()=>i[s],enumerable:!(f=fn(i,s))||f.enumerable});return n},en=(n,i,t)=>(t=n!=null?tn(gn(n)):{},mn(i||!n||!n.__esModule?W(t,"default",{value:n,enumerable:!0}):t,n)),vn=cn((n,i)=>{function t(o){if(typeof o!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(o))}function f(o,u){for(var r="",g=0,e=-1,m=0,C,v=0;v<=o.length;++v){if(v<o.length)C=o.charCodeAt(v);else{if(C===47)break;C=47}if(C===47){if(!(e===v-1||m===1))if(e!==v-1&&m===2){if(r.length<2||g!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){var $=r.lastIndexOf("/");if($!==r.length-1){$===-1?(r="",g=0):(r=r.slice(0,$),g=r.length-1-r.lastIndexOf("/")),e=v,m=0;continue}}else if(r.length===2||r.length===1){r="",g=0,e=v,m=0;continue}}u&&(r.length>0?r+="/..":r="..",g=2)}else r.length>0?r+="/"+o.slice(e+1,v):r=o.slice(e+1,v),g=v-e-1;e=v,m=0}else C===46&&m!==-1?++m:m=-1}return r}function s(o,u){var r=u.dir||u.root,g=u.base||(u.name||"")+(u.ext||"");return r?r===u.root?r+g:r+o+g:g}var c={resolve:function(){for(var o="",u=!1,r,g=arguments.length-1;g>=-1&&!u;g--){var e;g>=0?e=arguments[g]:(r===void 0&&(r=process.cwd()),e=r),t(e),e.length!==0&&(o=e+"/"+o,u=e.charCodeAt(0)===47)}return o=f(o,!u),u?o.length>0?"/"+o:"/":o.length>0?o:"."},normalize:function(o){if(t(o),o.length===0)return".";var u=o.charCodeAt(0)===47,r=o.charCodeAt(o.length-1)===47;return o=f(o,!u),o.length===0&&!u&&(o="."),o.length>0&&r&&(o+="/"),u?"/"+o:o},isAbsolute:function(o){return t(o),o.length>0&&o.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var o,u=0;u<arguments.length;++u){var r=arguments[u];t(r),r.length>0&&(o===void 0?o=r:o+="/"+r)}return o===void 0?".":c.normalize(o)},relative:function(o,u){if(t(o),t(u),o===u||(o=c.resolve(o),u=c.resolve(u),o===u))return"";for(var r=1;r<o.length&&o.charCodeAt(r)===47;++r);for(var g=o.length,e=g-r,m=1;m<u.length&&u.charCodeAt(m)===47;++m);for(var C=u.length,v=C-m,$=e<v?e:v,E=-1,A=0;A<=$;++A){if(A===$){if(v>$){if(u.charCodeAt(m+A)===47)return u.slice(m+A+1);if(A===0)return u.slice(m+A)}else e>$&&(o.charCodeAt(r+A)===47?E=A:A===0&&(E=0));break}var K=o.charCodeAt(r+A),M=u.charCodeAt(m+A);if(K!==M)break;K===47&&(E=A)}var F="";for(A=r+E+1;A<=g;++A)(A===g||o.charCodeAt(A)===47)&&(F.length===0?F+="..":F+="/..");return F.length>0?F+u.slice(m+E):(m+=E,u.charCodeAt(m)===47&&++m,u.slice(m))},_makeLong:function(o){return o},dirname:function(o){if(t(o),o.length===0)return".";for(var u=o.charCodeAt(0),r=u===47,g=-1,e=!0,m=o.length-1;m>=1;--m)if(u=o.charCodeAt(m),u===47){if(!e){g=m;break}}else e=!1;return g===-1?r?"/":".":r&&g===1?"//":o.slice(0,g)},basename:function(o,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');t(o);var r=0,g=-1,e=!0,m;if(u!==void 0&&u.length>0&&u.length<=o.length){if(u.length===o.length&&u===o)return"";var C=u.length-1,v=-1;for(m=o.length-1;m>=0;--m){var $=o.charCodeAt(m);if($===47){if(!e){r=m+1;break}}else v===-1&&(e=!1,v=m+1),C>=0&&($===u.charCodeAt(C)?--C===-1&&(g=m):(C=-1,g=v))}return r===g?g=v:g===-1&&(g=o.length),o.slice(r,g)}else{for(m=o.length-1;m>=0;--m)if(o.charCodeAt(m)===47){if(!e){r=m+1;break}}else g===-1&&(e=!1,g=m+1);return g===-1?"":o.slice(r,g)}},extname:function(o){t(o);for(var u=-1,r=0,g=-1,e=!0,m=0,C=o.length-1;C>=0;--C){var v=o.charCodeAt(C);if(v===47){if(!e){r=C+1;break}continue}g===-1&&(e=!1,g=C+1),v===46?u===-1?u=C:m!==1&&(m=1):u!==-1&&(m=-1)}return u===-1||g===-1||m===0||m===1&&u===g-1&&u===r+1?"":o.slice(u,g)},format:function(o){if(o===null||typeof o!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof o);return s("/",o)},parse:function(o){t(o);var u={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return u;var r=o.charCodeAt(0),g=r===47,e;g?(u.root="/",e=1):e=0;for(var m=-1,C=0,v=-1,$=!0,E=o.length-1,A=0;E>=e;--E){if(r=o.charCodeAt(E),r===47){if(!$){C=E+1;break}continue}v===-1&&($=!1,v=E+1),r===46?m===-1?m=E:A!==1&&(A=1):m!==-1&&(A=-1)}return m===-1||v===-1||A===0||A===1&&m===v-1&&m===C+1?v!==-1&&(C===0&&g?u.base=u.name=o.slice(1,v):u.base=u.name=o.slice(C,v)):(C===0&&g?(u.name=o.slice(1,m),u.base=o.slice(1,v)):(u.name=o.slice(C,m),u.base=o.slice(C,v)),u.ext=o.slice(m,v)),C>0?u.dir=o.slice(0,C-1):g&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};c.posix=c,i.exports=c}),B=en(vn()),L=B,Cn=B,Z=function(n){return n},J=function(){throw new Error("Not implemented")};L.parse??=J;Cn.parse??=J;var y={resolve:L.resolve.bind(L),normalize:L.normalize.bind(L),isAbsolute:L.isAbsolute.bind(L),join:L.join.bind(L),relative:L.relative.bind(L),toNamespacedPath:Z,dirname:L.dirname.bind(L),basename:L.basename.bind(L),extname:L.extname.bind(L),format:L.format.bind(L),parse:L.parse.bind(L),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:Z},V={sep:"\\",delimiter:";",win32:void 0,...y,posix:y};y.win32=V.win32=V;y.posix=y;var x=y;var{default:G}=(()=>({}));var R={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},S=(n,i,t)=>{let f=R[n]||R.reset,s=t?.method?R.method[t.method]||R.reset:R.reset,c=t?.status?t.status>=500?R.error:t.status>=400?R.warn:R.info:R.reset;console.log(`
|
|
2
|
-
${
|
|
3
|
-
`)},I=(n)=>{let{app:i,logger:t,logLevel:f="info",onRequest:s,onSend:c,onError:o,routeNotFound:u}=n||{};i?.addHooks("onRequest",(r,g)=>{r.startTime=Date.now(),t?.()??S(f,"Incoming Request",{method:r.method,url:g.toString(),headers:{"user-agent":r.headers.get("user-agent"),"content-type":r.headers.get("content-type")}}),s?.(r,g)}),i?.addHooks("onSend",async(r)=>{let g=`${Date.now()-r.req.startTime}ms`;t?.()??S(f,"Response Sent",{method:r.req.method,url:r.url.toString(),status:r.status,duration:g,headers:{"content-type":r.headers.get("content-type")}});let e=await c?.(r);if(e instanceof Response)return e}),i?.addHooks("routeNotFound",async(r)=>{t?.()??S("warn","Route Not Found",{method:r.req.method,url:r.url.toString(),status:404});let g=await u?.(r);if(g instanceof Response)return g}),i?.addHooks("onError",async(r,g,e)=>{t?.()??S("error","Unhandled Error",{method:g.method,url:e.toString(),status:500,error:r.message});let m=await o?.(r,g,e);if(m instanceof Response)return m})},O=(n,i,t,f=0,s)=>{let c=R.method[i]||R.reset,o=f>=500?R.error:f>=400?R.warn:R.info,u=n==="<--"?`${n} ${c}${i}${R.reset} ${t}`:`${n} ${c}${i}${R.reset} ${t} ${o}${f}${R.reset} ${s||""}`;console.log(u)},An=(n)=>{let i=Date.now()-n;return i<1000?`${i}ms`:`${Math.round(i/1000)}s`},Q=(n)=>{let{app:i,log:t,onRequest:f,onSend:s,onError:c,routeNotFound:o}=n;i.addHooks("onRequest",(u,r)=>{u.startTime=Date.now(),t?.()??O("<--",u.method,r.pathname),f?.(u,r)}),i.addHooks("onSend",async(u)=>{let{method:r,url:g}=u.req,e=new URL(g).pathname;t?.()??O("-->",r,e,u.status,An(u.req.startTime));let m=await s?.(u);if(m instanceof Response)return m}),i.addHooks("routeNotFound",async(u)=>{t?.()??O("[routeNotFound]",u.req.method,u.url.pathname,404);let r=await o?.(u);if(r instanceof Response)return r}),i.addHooks("onError",async(u,r,g)=>{t?.()??O(u.message,r.method,g.toString(),500);let e=await c?.(u,r,g);if(e instanceof Response)return e})};function _(n,i){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(t)=>{try{let f=t.cookies?.accessToken||t.req?.headers?.get("Authorization");if(!f)return t.json({message:"Unauthorized: No token provided"},401);if(f.startsWith("Bearer "))f=f.slice(7);let s=n?.verify(f,i);if(!s)return t.json({message:"Unauthorized: Invalid token"},401);t.set("user",s)}catch(f){return console.error("JWT verification error:",f),t.json({message:"Unauthorized: Invalid token",error:f?.message},401)}}}function j(n,i,t){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!i)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(f)=>{try{let s=f.cookies?.accessToken||f.req?.headers?.get("Authorization");if(!s)return f.json({message:"Unauthorized: No token provided"},401);if(s.startsWith("Bearer "))s=s.slice(7);let c=n?.verify(s,t);if(!c)return f.json({message:"Unauthorized: Invalid token"},401);let o=await i.findById(c._id).select("-password -refreshToken");if(!o)return f.json({message:"Unauthorized: User not found"},401);f.set("user",o);return}catch(s){return f.json({message:"Unauthorized: Authentication failed",error:s?.message},401)}}}class H{routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;constructor({jwtSecret:n,baseApiUrl:i,enableFileRouting:t,idleTimeOut:f}={}){this.routes={},this.idleTimeOut=f??10,this.enableFileRouter=t??!1,this.baseApiUrl=i||"",this.user_jwt_secret=n||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new N,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[],routeNotFound:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...n)=>{return this.FilterRoutes=n,this.setupFilter()},permitAll:()=>{for(let n of this?.FilterRoutes)this.filters.add(n);return this.FilterRoutes=null,this.setupFilter()},authenticate:(n)=>{if(n?.length)for(let i of n)this.filterFunction.push(i)},authenticateJwt:(n)=>{this.filterFunction.push(_(n,this.user_jwt_secret))},authenticateJwtDB:(n,i)=>{this.filterFunction.push(j(n,i,this.user_jwt_secret))}}}redirect(n,i,t){return this.any(n,(f)=>{let s=f.params,c=i;if(s)for(let u in s)c=c.replace(`:${u}`,s[u]);let o=f.url.search;if(o)c+=o;return f.redirect(c,t)}),this}serveStatic(n){return this.staticPath=n,this}staticHtml(n){return this.staticFiles={...this.staticFiles,...n},this}addHooks(n,i){if(typeof n!=="string")throw new Error("hookName must be a string");if(typeof i!=="function")throw new Error("callback must be a instance of function");switch(n){case"onRequest":this.hooks.onRequest?.push(i);break;case"preHandler":this.hooks.preHandler?.push(i);break;case"postHandler":this.hooks.postHandler?.push(i);break;case"onSend":this.hooks.onSend?.push(i);break;case"onError":this.hooks.onError?.push(i);break;case"onClose":this.hooks.onClose?.push(i);break;case"routeNotFound":this.hooks.routeNotFound?.push(i);break;default:throw new Error(`Unknown hook type: ${n}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[n,i]of this.middlewares.entries())if(i.length>0){this.hasMiddleware=!0;break}if(this.enableFileRouter){let n=process.cwd(),i=x.join(n,"src","routes");if(G?.existsSync(i))this.loadRoutes(i,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(n,i,t){let f=await import(n),s;if(t===".ts")s=x.basename(n,".ts");else if(t===".js")s=x.basename(n,".js");let c=i+"/"+s;if(c.endsWith("/index"))c=i;else if(c.endsWith("/api"))c=i;c=c.replace(/\[(.*?)\]/g,":$1");let o=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let u of o)if(f[u]){let r=u.toLowerCase(),g=f[u];this[r](`${this.baseApiUrl}${c}`,g)}}async loadRoutes(n,i){let t=await G.promises.readdir(n);for(let f of t){let s=x.join(n,f);if((await G.promises.stat(s)).isDirectory())this.loadRoutes(s,i+"/"+f);else if(f.endsWith(".ts"))this.registerFileRoutes(s,i,".ts");else if(f.endsWith(".js"))this.registerFileRoutes(s,i,".js")}}useLogger(n){return Q(n),this}useAdvancedLogger(n){return I(n),this}BunRoute(n,i,...t){if(!i||typeof i!=="string")throw new Error("give a path in string format");if(t.length===1){let f=t[0];this.routes[i]=async(s,c)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let r=await b(this.globalMiddlewares,s,c);if(r)return r}let u=this.middlewares.get(i)||[];if(u?.length){let r=await b(u,s,c);if(r)return r}}if(n!==s.method)return new Response("Method Not Allowed",{status:405});let o=await f(s,c);if(o instanceof Promise)return await o??new Response("Not Found",{status:404});return o??new Response("Not Found",{status:404})}}else this.routes[i]=async(f,s)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let o=await b(this.globalMiddlewares,f,s);if(o)return o}let c=this.middlewares.get(i)||[];if(c?.length){let o=await b(c,f,s);if(o)return o}}if(n!==f.method)return new Response("Method Not Allowed",{status:405});for(let c=0;c<t.length;c++){let o=t[c](f,s);if(o instanceof Promise)return await o??new Response("Not Found",{status:404});return o??new Response("Not Found",{status:404})}}}listen(n,...i){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let t="0.0.0.0",f=void 0,s={};for(let o of i)if(typeof o==="string")t=o;else if(typeof o==="function")f=o;else if(typeof o==="object"&&o!==null)s=o;this.compile();let c={port:n,hostname:t,idleTimeOut:this.idleTimeOut,fetch:async(o,u)=>{let r=new URL(o.url);if(this.hooks.onRequest){let g=this.hooks.onRequest;for(let e=0;e<g.length;e++)await g[e](o,r,u)}return U(o,u,r,this)},static:this.staticFiles,routes:this.routes};if(s.sslCert&&s.sslKey)c.certFile=s.sslCert,c.keyFile=s.sslKey;if(this.serverInstance=Bun?.serve(c),s.sslCert&&s.sslKey)console.log(`HTTPS server is running on https://localhost:${n}`);if(f)return f();return this.serverInstance}close(n){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,n?n():console.log("Server has been stopped");else console.warn("Server is not running.")}route(n,i){if(!n||typeof n!=="string")throw new Error("Path must be a string");let t=Object.fromEntries(i.tempRoutes);return Object.entries(t).forEach(([s,c])=>{let o=s.replace(/::\w+$/,""),u=`${n}${o}`;if(!this.middlewares.has(u))this.middlewares.set(u,[]);c.handlers.slice(0,-1).forEach((m)=>{if(!this.middlewares.get(u)?.includes(m))this.middlewares.get(u)?.push(m)});let g=c.handlers[c.handlers.length-1],e=c.method;try{this.trie.insert(u,{handler:g,method:e})}catch(m){console.error(`Error inserting ${u}:`,m)}}),i=null,this}register(n,i){return this.route(n,i)}addRoute(n,i,t){if(typeof i!=="string")throw new Error(`Error in ${t[t.length-1]}: Path must be a string. Received: ${typeof i}`);if(typeof n!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof n}`);this.tempRoutes?.set(i+"::"+n,{method:n,handlers:t});let f=t.slice(0,-1),s=t[t.length-1];if(!this.middlewares.has(i))this.middlewares.set(i,[]);f.forEach((c)=>{if(i==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...f])];else if(!this.middlewares.get(i)?.includes(c))this.middlewares.get(i)?.push(c)});try{if(n==="ANY"){let c=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let o of c)this.trie.insert(i,{handler:s,method:o})}this.trie.insert(i,{handler:s,method:n})}catch(c){console.error(`Error inserting ${i}:`,c)}}use(n,i){if(Array.isArray(n))n.forEach((f)=>{if(typeof f==="function")this.globalMiddlewares.push(f)});if(typeof n==="function"){if(this.globalMiddlewares.push(n),Array.isArray(i))i.forEach((f)=>{this.globalMiddlewares.push(f)});return}return(Array.isArray(n)?n.filter((f)=>typeof f==="string"):[n].filter((f)=>typeof f==="string")).forEach((f)=>{if(!this.middlewares.has(f))this.middlewares.set(f,[]);if(i)(Array.isArray(i)?i:[i]).forEach((c)=>{this.middlewares.get(f)?.push(c)})}),this}get(n,...i){return this.addRoute("GET",n,i),this}post(n,...i){return this.addRoute("POST",n,i),this}put(n,...i){return this.addRoute("PUT",n,i),this}patch(n,...i){return this.addRoute("PATCH",n,i),this}delete(n,...i){return this.addRoute("DELETE",n,i),this}any(n,...i){return this.addRoute("ANY",n,i),this}head(n,...i){return this.addRoute("HEAD",n,i),this}options(n,...i){return this.addRoute("OPTIONS",n,i),this}propfind(n,...i){return this.addRoute("PROPFIND",n,i),this}}export{H as default};
|
|
1
|
+
var o=Object.create;var{getPrototypeOf:l,defineProperty:O,getOwnPropertyNames:d}=Object;var s=Object.prototype.hasOwnProperty;var a=(A,G,K)=>{K=A!=null?o(l(A)):{};let X=G||!A||!A.__esModule?O(K,"default",{value:A,enumerable:!0}):K;for(let $ of d(A))if(!s.call(X,$))O(X,$,{get:()=>A[$],enumerable:!0});return X};var r=((A)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(A,{get:(G,K)=>(typeof require!=="undefined"?require:G)[K]}):A)(function(A){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});class f{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class C{root;constructor(){this.root=new f}insert(A,G){let K=this.root,X=A.split("/").filter(Boolean);if(A==="/"){K.isEndOfWord=!0,K.handler.push(G.handler),K.path=A,K.method.push(G.method);return}for(let $ of X){let V=!1,z=$;if($.startsWith(":"))V=!0,z=":";if(!K.children[z])K.children[z]=new f;K=K.children[z],K.isDynamic=V,K.pattern=$}K.isEndOfWord=!0,K.path=A,K.method.push(G.method),K.handler.push(G.handler)}search(A,G){let K=this.root,X=A.split("/").filter(Boolean),$=X.length;for(let Y of X){let v=Y;if(!K.children[v])if(K.children[":"])K=K.children[":"];else return null;else K=K.children[v]}let V=K.path.split("/").filter(Boolean);if($!==V.length)return null;let z=K.method.indexOf(G);if(z!==-1)return{path:K.path,handler:K.handler[z],isDynamic:K.isDynamic,pattern:K.pattern,method:K.method[z]};return{path:K.path,handler:K.handler,isDynamic:K.isDynamic,pattern:K.pattern,method:K.method[z]}}}function L(A){switch(A.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function g(A,G,K){let X=null,$=null,V=null,z=null,Y={};return{req:A,server:G,url:K,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(v,Z){return this.headers.set(v,Z),this},removeHeader(v){return this.headers.delete(v),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!X)try{X=Object.fromEntries(this.url.searchParams)}catch(v){throw new Error("Failed to parse query parameters")}return X},get params(){if(!$&&this.req.routePattern)try{$=e(this.req.routePattern,this.url.pathname)}catch(v){throw new Error("Failed to extract route parameters")}return $??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!z)z=(async()=>{let v=await A1(this.req);if(v.error)throw new Error(v.error);return Object.keys(v).length===0?null:v})();return z},set(v,Z){return Y[v]=Z,this},get(v){return Y[v]},text(v,Z){if(Z)this.status=Z;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(v,{status:this.status,headers:this.headers})},send(v,Z){if(Z)this.status=Z;let N=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),b;if(v instanceof Uint8Array)b="Uint8Array";else if(v instanceof ArrayBuffer)b="ArrayBuffer";else b=typeof v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",N.get(b)??"text/plain; charset=utf-8");let J=b==="object"&&v!==null?JSON.stringify(v):v;return new Response(J,{status:this.status,headers:this.headers})},json(v,Z){if(Z)this.status=Z;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(v,{status:this.status,headers:this.headers})},file(v,Z,N){if(N)this.status=N;let b=Bun.file(v);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Z??L(v));return new Response(b,{status:this.status,headers:this.headers})},async ejs(v,Z={},N){if(N)this.status=N;let b;try{b=await import("ejs"),b=b.default||b}catch(J){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let J=await Bun.file(v).text(),W=b.render(J,Z),B=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(W,{status:this.status,headers:B})}catch(J){return console.error("EJS Rendering Error:",J),new Response("Error rendering template",{status:500})}},redirect(v,Z){if(Z)this.status=Z;else this.status=302;return this.headers.set("Location",v),new Response(null,{status:this.status,headers:this.headers})},stream(v){let Z=new Headers(this.headers),N=new ReadableStream({async start(b){await v(b),b.close()}});return new Response(N,{headers:Z})},yieldStream(v){return new Response({async*[Symbol.asyncIterator](){yield*v()}},{headers:this.headers})},setCookie(v,Z,N={}){let b=`${encodeURIComponent(v)}=${encodeURIComponent(Z)}`;if(N.maxAge)b+=`; Max-Age=${N.maxAge}`;if(N.expires)b+=`; Expires=${N.expires.toUTCString()}`;if(N.path)b+=`; Path=${N.path}`;if(N.domain)b+=`; Domain=${N.domain}`;if(N.secure)b+="; Secure";if(N.httpOnly)b+="; HttpOnly";if(N.sameSite)b+=`; SameSite=${N.sameSite}`;return this.headers.append("Set-Cookie",b),this},get cookies(){if(!V){let v=this.req.headers.get("cookie");V=v?t(v):{}}return V}}}function t(A){return Object.fromEntries(A.split(";").map((G)=>{let[K,...X]=G.trim().split("=");return[K,decodeURIComponent(X.join("="))]}))}function e(A,G){let K={},X=A.split("/"),[$]=G.split("?"),V=$.split("/");if(X.length!==V.length)return null;for(let z=0;z<X.length;z++)if(X[z].startsWith(":"))K[X[z].slice(1)]=V[z];return K}async function A1(A){let G=A.headers.get("Content-Type");if(!G)return{};if(A.headers.get("Content-Length")==="0"||!A.body)return{};try{if(G.startsWith("application/json"))return await A.json();if(G.startsWith("application/x-www-form-urlencoded")){let X=await A.text();return Object.fromEntries(new URLSearchParams(X))}if(G.startsWith("multipart/form-data")){let X=await A.formData(),$={};for(let[V,z]of X.entries())$[V]=z;return $}return{error:"Unknown request body type"}}catch(X){return{error:"Invalid request body format"}}}async function y(A,G,K,X){let $=g(A,G,K),V=X.trie.search(K.pathname,A.method);A.routePattern=V?.path;try{if(X.hasFilterEnabled){let v=A.routePattern??K.pathname,Z=await z1(X,v,$,G),N=Z instanceof Promise?await Z:Z;if(N)return N}if(X.hasMiddleware){if(X.globalMiddlewares.length){let Z=await P(X.globalMiddlewares,$,G);if(Z)return Z}let v=X.middlewares.get(K.pathname)||[];if(v?.length){let Z=await P(v,$,G);if(Z)return Z}}if(!V?.handler||V.method!==A.method){if(X.staticPath){let v=await v1(X,K.pathname,$);if(v)return v;let Z=X.trie.search("*",A.method);if(Z?.handler)return await Z.handler($)}if(X.hooks.routeNotFound&&Array.isArray(X.hooks.routeNotFound)&&!V?.handler){let v=X.hooks.routeNotFound;for(let Z=0;Z<v.length;Z++){let N=v[Z]($),b=N instanceof Promise?await N:N;if(b)return b}}if(!V||!V?.handler?.length)return T(404,`Route not found for ${K.pathname}`);if(V?.method!==A.method)return T(405,"Method not allowed")}if(X.hooks.preHandler?.length&&Array.isArray(X.hooks.preHandler)){let v=X.hooks.preHandler;for(let Z=0;Z<v.length;Z++){let N=v[Z]($),b=N instanceof Promise?await N:N;if(b)return b}}let z=V.handler($);return(z instanceof Promise?await z:z)??T(204,"")}catch(z){if(X.hooks.onError&&Array.isArray(X.hooks.onError)){let Y=X.hooks.onError;for(let v=0;v<Y.length;v++){let Z=X.hooks.onError[v](z,A,K,G),N=Z instanceof Promise?await Z:Z;if(N)return N}}return T(500,"Internal Server Error")}finally{if(X.hooks.onSend&&Array.isArray(X.hooks.onSend)){let z=X.hooks.onSend;for(let Y=0;Y<z.length;Y++){let v=z[Y]($),Z=v instanceof Promise?await v:v;if(Z)return Z}}}}async function P(A,G,K){for(let X of A){let $=await X(G,K);if($)return $}return null}async function j(A,G,K){for(let X of A){let $=await X(G,K);if($)return $}}async function z1(A,G,K,X){if(!A.filters.has(G))if(A.filterFunction.length)for(let $ of A.filterFunction){let V=await $(K,X);if(V)return V}else return Response.json({error:!0,message:"Protected route, authentication required",status:401},{status:401})}async function j1(A,G,K,X){if(!A.filters.has(G))if(A.filterFunction.length)for(let $ of A.filterFunction){let V=await $(K,X);if(V)return V}else return Response.json({error:!0,message:"Protected route, authentication required",status:401},{status:401})}function T(A,G){return new Response(JSON.stringify({error:!0,message:G,status:A}),{status:A,headers:{"Content-Type":"application/json"}})}async function v1(A,G,K){if(!A.staticPath)return null;let X=`${A.staticPath}${G}`;if(await Bun.file(X).exists()){let V=L(X);return K.file(X,V,200)}return null}var{create:G1,defineProperty:m,getOwnPropertyDescriptor:K1,getOwnPropertyNames:X1,getPrototypeOf:Y1}=Object,Z1=Object.prototype.hasOwnProperty,$1=(A,G)=>()=>(G||A((G={exports:{}}).exports,G),G.exports),b1=(A,G,K,X)=>{if(G&&typeof G=="object"||typeof G=="function")for(let $ of X1(G))!Z1.call(A,$)&&$!==K&&m(A,$,{get:()=>G[$],enumerable:!(X=K1(G,$))||X.enumerable});return A},V1=(A,G,K)=>(K=A!=null?G1(Y1(A)):{},b1(G||!A||!A.__esModule?m(K,"default",{value:A,enumerable:!0}):K,A)),N1=$1((A,G)=>{function K(z){if(typeof z!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(z))}function X(z,Y){for(var v="",Z=0,N=-1,b=0,J,W=0;W<=z.length;++W){if(W<z.length)J=z.charCodeAt(W);else{if(J===47)break;J=47}if(J===47){if(!(N===W-1||b===1))if(N!==W-1&&b===2){if(v.length<2||Z!==2||v.charCodeAt(v.length-1)!==46||v.charCodeAt(v.length-2)!==46){if(v.length>2){var B=v.lastIndexOf("/");if(B!==v.length-1){B===-1?(v="",Z=0):(v=v.slice(0,B),Z=v.length-1-v.lastIndexOf("/")),N=W,b=0;continue}}else if(v.length===2||v.length===1){v="",Z=0,N=W,b=0;continue}}Y&&(v.length>0?v+="/..":v="..",Z=2)}else v.length>0?v+="/"+z.slice(N+1,W):v=z.slice(N+1,W),Z=W-N-1;N=W,b=0}else J===46&&b!==-1?++b:b=-1}return v}function $(z,Y){var v=Y.dir||Y.root,Z=Y.base||(Y.name||"")+(Y.ext||"");return v?v===Y.root?v+Z:v+z+Z:Z}var V={resolve:function(){for(var z="",Y=!1,v,Z=arguments.length-1;Z>=-1&&!Y;Z--){var N;Z>=0?N=arguments[Z]:(v===void 0&&(v=process.cwd()),N=v),K(N),N.length!==0&&(z=N+"/"+z,Y=N.charCodeAt(0)===47)}return z=X(z,!Y),Y?z.length>0?"/"+z:"/":z.length>0?z:"."},normalize:function(z){if(K(z),z.length===0)return".";var Y=z.charCodeAt(0)===47,v=z.charCodeAt(z.length-1)===47;return z=X(z,!Y),z.length===0&&!Y&&(z="."),z.length>0&&v&&(z+="/"),Y?"/"+z:z},isAbsolute:function(z){return K(z),z.length>0&&z.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var z,Y=0;Y<arguments.length;++Y){var v=arguments[Y];K(v),v.length>0&&(z===void 0?z=v:z+="/"+v)}return z===void 0?".":V.normalize(z)},relative:function(z,Y){if(K(z),K(Y),z===Y||(z=V.resolve(z),Y=V.resolve(Y),z===Y))return"";for(var v=1;v<z.length&&z.charCodeAt(v)===47;++v);for(var Z=z.length,N=Z-v,b=1;b<Y.length&&Y.charCodeAt(b)===47;++b);for(var J=Y.length,W=J-b,B=N<W?N:W,D=-1,Q=0;Q<=B;++Q){if(Q===B){if(W>B){if(Y.charCodeAt(b+Q)===47)return Y.slice(b+Q+1);if(Q===0)return Y.slice(b+Q)}else N>B&&(z.charCodeAt(v+Q)===47?D=Q:Q===0&&(D=0));break}var w=z.charCodeAt(v+Q),h=Y.charCodeAt(b+Q);if(w!==h)break;w===47&&(D=Q)}var U="";for(Q=v+D+1;Q<=Z;++Q)(Q===Z||z.charCodeAt(Q)===47)&&(U.length===0?U+="..":U+="/..");return U.length>0?U+Y.slice(b+D):(b+=D,Y.charCodeAt(b)===47&&++b,Y.slice(b))},_makeLong:function(z){return z},dirname:function(z){if(K(z),z.length===0)return".";for(var Y=z.charCodeAt(0),v=Y===47,Z=-1,N=!0,b=z.length-1;b>=1;--b)if(Y=z.charCodeAt(b),Y===47){if(!N){Z=b;break}}else N=!1;return Z===-1?v?"/":".":v&&Z===1?"//":z.slice(0,Z)},basename:function(z,Y){if(Y!==void 0&&typeof Y!="string")throw new TypeError('"ext" argument must be a string');K(z);var v=0,Z=-1,N=!0,b;if(Y!==void 0&&Y.length>0&&Y.length<=z.length){if(Y.length===z.length&&Y===z)return"";var J=Y.length-1,W=-1;for(b=z.length-1;b>=0;--b){var B=z.charCodeAt(b);if(B===47){if(!N){v=b+1;break}}else W===-1&&(N=!1,W=b+1),J>=0&&(B===Y.charCodeAt(J)?--J===-1&&(Z=b):(J=-1,Z=W))}return v===Z?Z=W:Z===-1&&(Z=z.length),z.slice(v,Z)}else{for(b=z.length-1;b>=0;--b)if(z.charCodeAt(b)===47){if(!N){v=b+1;break}}else Z===-1&&(N=!1,Z=b+1);return Z===-1?"":z.slice(v,Z)}},extname:function(z){K(z);for(var Y=-1,v=0,Z=-1,N=!0,b=0,J=z.length-1;J>=0;--J){var W=z.charCodeAt(J);if(W===47){if(!N){v=J+1;break}continue}Z===-1&&(N=!1,Z=J+1),W===46?Y===-1?Y=J:b!==1&&(b=1):Y!==-1&&(b=-1)}return Y===-1||Z===-1||b===0||b===1&&Y===Z-1&&Y===v+1?"":z.slice(Y,Z)},format:function(z){if(z===null||typeof z!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof z);return $("/",z)},parse:function(z){K(z);var Y={root:"",dir:"",base:"",ext:"",name:""};if(z.length===0)return Y;var v=z.charCodeAt(0),Z=v===47,N;Z?(Y.root="/",N=1):N=0;for(var b=-1,J=0,W=-1,B=!0,D=z.length-1,Q=0;D>=N;--D){if(v=z.charCodeAt(D),v===47){if(!B){J=D+1;break}continue}W===-1&&(B=!1,W=D+1),v===46?b===-1?b=D:Q!==1&&(Q=1):b!==-1&&(Q=-1)}return b===-1||W===-1||Q===0||Q===1&&b===W-1&&b===J+1?W!==-1&&(J===0&&Z?Y.base=Y.name=z.slice(1,W):Y.base=Y.name=z.slice(J,W)):(J===0&&Z?(Y.name=z.slice(1,b),Y.base=z.slice(1,W)):(Y.name=z.slice(J,b),Y.base=z.slice(J,W)),Y.ext=z.slice(b,W)),J>0?Y.dir=z.slice(0,J-1):Z&&(Y.dir="/"),Y},sep:"/",delimiter:":",win32:null,posix:null};V.posix=V,G.exports=V}),q=V1(N1()),E=q,W1=q,k=function(A){return A},c=function(){throw new Error("Not implemented")};E.parse??=c;W1.parse??=c;var I={resolve:E.resolve.bind(E),normalize:E.normalize.bind(E),isAbsolute:E.isAbsolute.bind(E),join:E.join.bind(E),relative:E.relative.bind(E),toNamespacedPath:k,dirname:E.dirname.bind(E),basename:E.basename.bind(E),extname:E.extname.bind(E),format:E.format.bind(E),parse:E.parse.bind(E),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:k},x={sep:"\\",delimiter:";",win32:void 0,...I,posix:I};I.win32=x.win32=x;I.posix=I;var F=I;var{default:S}=(()=>({}));var _={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},H=(A,G,K)=>{let X=_[A]||_.reset,$=K?.method?_.method[K.method]||_.reset:_.reset,V=K?.status?K.status>=500?_.error:K.status>=400?_.warn:_.info:_.reset;console.log(`
|
|
2
|
+
${X}[${A.toUpperCase()}]${_.reset} ${G} - ${$}${K?.method||""}${_.reset}`);let z={timestamp:new Date().toISOString(),...K,status:K?.status?`${V}${K.status}${_.reset}`:void 0,method:K?.method?`${$}${K.method}${_.reset}`:void 0};console.log(JSON.stringify(z,null,2)+`
|
|
3
|
+
`)},R=(A)=>{let{app:G,logger:K,logLevel:X="info",onRequest:$,onSend:V,onError:z,routeNotFound:Y}=A||{};G?.addHooks("onRequest",(v,Z)=>{v.startTime=Date.now(),K?.()??H(X,"Incoming Request",{method:v.method,url:Z.toString(),headers:{"user-agent":v.headers.get("user-agent"),"content-type":v.headers.get("content-type")}}),$?.(v,Z)}),G?.addHooks("onSend",async(v)=>{let Z=`${Date.now()-v.req.startTime}ms`;K?.()??H(X,"Response Sent",{method:v.req.method,url:v.url.toString(),status:v.status,duration:Z,headers:{"content-type":v.headers.get("content-type")}});let N=await V?.(v);if(N instanceof Response)return N}),G?.addHooks("onError",async(v,Z,N)=>{K?.()??H("error","Unhandled Error",{method:Z.method,url:N.toString(),status:500,error:v.message});let b=await z?.(v,Z,N);if(b instanceof Response)return b})},M=(A,G,K,X=0,$)=>{let V=_.method[G]||_.reset,z=X>=500?_.error:X>=400?_.warn:_.info,Y=A==="<--"?`${A} ${V}${G}${_.reset} ${K}`:`${A} ${V}${G}${_.reset} ${K} ${z}${X}${_.reset} ${$||""}`;console.log(Y)},J1=(A)=>{let G=Date.now()-A;return G<1000?`${G}ms`:`${Math.round(G/1000)}s`},u=(A)=>{let{app:G,log:K,onRequest:X,onSend:$,onError:V,routeNotFound:z}=A;G.addHooks("onRequest",(Y,v)=>{Y.startTime=Date.now(),K?.()??M("<--",Y.method,v.pathname),X?.(Y,v)}),G.addHooks("onSend",async(Y)=>{let{method:v,url:Z}=Y.req,N=new URL(Z).pathname;K?.()??M("-->",v,N,Y.status,J1(Y.req.startTime));let b=await $?.(Y);if(b instanceof Response)return b}),G.addHooks("onError",async(Y,v,Z)=>{K?.()??M(Y.message,v.method,Z.toString(),500);let N=await V?.(Y,v,Z);if(N instanceof Response)return N})};function i(A,G){if(!A)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(K)=>{try{let X=K.cookies?.accessToken??K.req?.headers?.get("Authorization");if(!X)return K.json({message:"Unauthorized",error:"No token provided"},401);if(X.startsWith("Bearer "))X=X.slice(7);let $=A?.verify(X,G);if(!$)return K.json({message:"Unauthorized",error:"Token could not be decoded"},401);K.set("user",$)}catch(X){let $="Invalid token";if(X.name==="TokenExpiredError")$="Token expired";else if(X.name==="JsonWebTokenError")$="Malformed or tampered token";return K.json({message:"Unauthorized",error:$},401)}}}function n(A,G,K){if(!A)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!G)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(X)=>{try{let $=X.cookies?.accessToken??X.req?.headers?.get("Authorization");if(!$)return X.json({message:"Unauthorized",error:"No token provided"},401);if($.startsWith("Bearer "))$=$.slice(7);let V=A?.verify($,K);if(!V)return X.json({message:"Unauthorized",error:"Token could not be decoded"},401);let z=await G.findById(V._id).select("-password -refreshToken");if(!z)return X.json({message:"Unauthorized: User not found"},404);X.set("user",z);return}catch($){let V="Invalid token";if($.name==="TokenExpiredError")V="Token expired";else if($.name==="JsonWebTokenError")V="Malformed or tampered token";return X.json({message:"Unauthorized",error:V},401)}}}class p{routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;constructor({jwtSecret:A,baseApiUrl:G,enableFileRouting:K,idleTimeOut:X}={}){this.routes={},this.idleTimeOut=X??10,this.enableFileRouter=K??!1,this.baseApiUrl=G||"",this.user_jwt_secret=A||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new C,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[],routeNotFound:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...A)=>{return this.FilterRoutes=A,this.setupFilter()},permitAll:()=>{for(let A of this?.FilterRoutes)this.filters.add(A);return this.FilterRoutes=null,this.setupFilter()},authenticate:(A)=>{if(A?.length)for(let G of A)this.filterFunction.push(G)},authenticateJwt:(A)=>{this.filterFunction.push(i(A,this.user_jwt_secret))},authenticateJwtDB:(A,G)=>{this.filterFunction.push(n(A,G,this.user_jwt_secret))}}}redirect(A,G,K){return this.any(A,(X)=>{let $=X.params,V=G;if($)for(let Y in $)V=V.replace(`:${Y}`,$[Y]);let z=X.url.search;if(z)V+=z;return X.redirect(V,K)}),this}serveStatic(A){return this.staticPath=A,this}staticHtml(A){return this.staticFiles={...this.staticFiles,...A},this}addHooks(A,G){if(typeof A!=="string")throw new Error("hookName must be a string");if(typeof G!=="function")throw new Error("callback must be a instance of function");switch(A){case"onRequest":this.hooks.onRequest?.push(G);break;case"preHandler":this.hooks.preHandler?.push(G);break;case"postHandler":this.hooks.postHandler?.push(G);break;case"onSend":this.hooks.onSend?.push(G);break;case"onError":this.hooks.onError?.push(G);break;case"onClose":this.hooks.onClose?.push(G);break;case"routeNotFound":this.hooks.routeNotFound?.push(G);break;default:throw new Error(`Unknown hook type: ${A}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[A,G]of this.middlewares.entries())if(G.length>0){this.hasMiddleware=!0;break}if(this.enableFileRouter){let A=process.cwd(),G=F.join(A,"src","routes");if(S?.existsSync(G))this.loadRoutes(G,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(A,G,K){let X=await import(A),$;if(K===".ts")$=F.basename(A,".ts");else if(K===".js")$=F.basename(A,".js");let V=G+"/"+$;if(V.endsWith("/index"))V=G;else if(V.endsWith("/api"))V=G;V=V.replace(/\[(.*?)\]/g,":$1");let z=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let Y of z)if(X[Y]){let v=Y.toLowerCase(),Z=X[Y];this[v](`${this.baseApiUrl}${V}`,Z)}}async loadRoutes(A,G){let K=await S.promises.readdir(A);for(let X of K){let $=F.join(A,X);if((await S.promises.stat($)).isDirectory())this.loadRoutes($,G+"/"+X);else if(X.endsWith(".ts"))this.registerFileRoutes($,G,".ts");else if(X.endsWith(".js"))this.registerFileRoutes($,G,".js")}}useLogger(A){return u(A),this}useAdvancedLogger(A){return R(A),this}BunRoute(A,G,...K){if(!G||typeof G!=="string")throw new Error("give a path in string format");if(K.length===1){let X=K[0];this.routes[G]=async($,V)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let v=await j(this.globalMiddlewares,$,V);if(v)return v}let Y=this.middlewares.get(G)||[];if(Y?.length){let v=await j(Y,$,V);if(v)return v}}if(A!==$.method)return new Response("Method Not Allowed",{status:405});let z=await X($,V);if(z instanceof Promise)return await z??new Response("Not Found",{status:404});return z??new Response("Not Found",{status:404})}}else this.routes[G]=async(X,$)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let z=await j(this.globalMiddlewares,X,$);if(z)return z}let V=this.middlewares.get(G)||[];if(V?.length){let z=await j(V,X,$);if(z)return z}}if(A!==X.method)return new Response("Method Not Allowed",{status:405});for(let V=0;V<K.length;V++){let z=K[V](X,$);if(z instanceof Promise)return await z??new Response("Not Found",{status:404});return z??new Response("Not Found",{status:404})}}}listen(A,...G){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let K="0.0.0.0",X=void 0,$={};for(let z of G)if(typeof z==="string")K=z;else if(typeof z==="function")X=z;else if(typeof z==="object"&&z!==null)$=z;this.compile();let V={port:A,hostname:K,idleTimeOut:this.idleTimeOut,fetch:async(z,Y)=>{let v=new URL(z.url);if(this.hooks.onRequest){let Z=this.hooks.onRequest;for(let N=0;N<Z.length;N++)await Z[N](z,v,Y)}return y(z,Y,v,this)},static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)console.log(this.routes),V.routes=this.routes;if($.sslCert&&$.sslKey)V.certFile=$.sslCert,V.keyFile=$.sslKey;if(this.serverInstance=Bun?.serve(V),$.sslCert&&$.sslKey)console.log(`HTTPS server is running on https://localhost:${A}`);if(X)return X();return this.serverInstance}close(A){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,A?A():console.log("Server has been stopped");else console.warn("Server is not running.")}route(A,G){if(!A||typeof A!=="string")throw new Error("Path must be a string");let K=Object.fromEntries(G.tempRoutes);return Object.entries(K).forEach(([$,V])=>{let z=$.replace(/::\w+$/,""),Y=`${A}${z}`;if(!this.middlewares.has(Y))this.middlewares.set(Y,[]);V.handlers.slice(0,-1).forEach((b)=>{if(!this.middlewares.get(Y)?.includes(b))this.middlewares.get(Y)?.push(b)});let Z=V.handlers[V.handlers.length-1],N=V.method;try{this.trie.insert(Y,{handler:Z,method:N})}catch(b){console.error(`Error inserting ${Y}:`,b)}}),G=null,this}register(A,G){return this.route(A,G)}addRoute(A,G,K){if(typeof G!=="string")throw new Error(`Error in ${K[K.length-1]}: Path must be a string. Received: ${typeof G}`);if(typeof A!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof A}`);this.tempRoutes?.set(G+"::"+A,{method:A,handlers:K});let X=K.slice(0,-1),$=K[K.length-1];if(!this.middlewares.has(G))this.middlewares.set(G,[]);X.forEach((V)=>{if(G==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...X])];else if(!this.middlewares.get(G)?.includes(V))this.middlewares.get(G)?.push(V)});try{if(A==="ANY"){let V=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let z of V)this.trie.insert(G,{handler:$,method:z})}this.trie.insert(G,{handler:$,method:A})}catch(V){console.error(`Error inserting ${G}:`,V)}}use(A,G){if(Array.isArray(A))A.forEach((X)=>{if(typeof X==="function")this.globalMiddlewares.push(X)});if(typeof A==="function"){if(this.globalMiddlewares.push(A),Array.isArray(G))G.forEach((X)=>{this.globalMiddlewares.push(X)});return}return(Array.isArray(A)?A.filter((X)=>typeof X==="string"):[A].filter((X)=>typeof X==="string")).forEach((X)=>{if(!this.middlewares.has(X))this.middlewares.set(X,[]);if(G)(Array.isArray(G)?G:[G]).forEach((V)=>{this.middlewares.get(X)?.push(V)})}),this}get(A,...G){return this.addRoute("GET",A,G),this}post(A,...G){return this.addRoute("POST",A,G),this}put(A,...G){return this.addRoute("PUT",A,G),this}patch(A,...G){return this.addRoute("PATCH",A,G),this}delete(A,...G){return this.addRoute("DELETE",A,G),this}any(A,...G){return this.addRoute("ANY",A,G),this}head(A,...G){return this.addRoute("HEAD",A,G),this}options(A,...G){return this.addRoute("OPTIONS",A,G),this}propfind(A,...G){return this.addRoute("PROPFIND",A,G),this}}export{p as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var{create:D,defineProperty:P,getOwnPropertyDescriptor:L,getOwnPropertyNames:$,getPrototypeOf:H}=Object,J=Object.prototype.hasOwnProperty,M=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),X=(o,i,l,g)=>{if(i&&typeof i=="object"||typeof i=="function")for(let v of $(i))!J.call(o,v)&&v!==l&&P(o,v,{get:()=>i[v],enumerable:!(g=L(i,v))||g.enumerable});return o},q=(o,i,l)=>(l=o!=null?D(H(o)):{},X(i||!o||!o.__esModule?P(l,"default",{value:o,enumerable:!0}):l,o)),F=M((o,i)=>{function l(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function g(e,t){for(var r="",a=0,u=-1,n=0,
|
|
1
|
+
var{create:D,defineProperty:P,getOwnPropertyDescriptor:L,getOwnPropertyNames:$,getPrototypeOf:H}=Object,J=Object.prototype.hasOwnProperty,M=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),X=(o,i,l,g)=>{if(i&&typeof i=="object"||typeof i=="function")for(let v of $(i))!J.call(o,v)&&v!==l&&P(o,v,{get:()=>i[v],enumerable:!(g=L(i,v))||g.enumerable});return o},q=(o,i,l)=>(l=o!=null?D(H(o)):{},X(i||!o||!o.__esModule?P(l,"default",{value:o,enumerable:!0}):l,o)),F=M((o,i)=>{function l(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function g(e,t){for(var r="",a=0,u=-1,n=0,c,s=0;s<=e.length;++s){if(s<e.length)c=e.charCodeAt(s);else{if(c===47)break;c=47}if(c===47){if(!(u===s-1||n===1))if(u!==s-1&&n===2){if(r.length<2||a!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){var f=r.lastIndexOf("/");if(f!==r.length-1){f===-1?(r="",a=0):(r=r.slice(0,f),a=r.length-1-r.lastIndexOf("/")),u=s,n=0;continue}}else if(r.length===2||r.length===1){r="",a=0,u=s,n=0;continue}}t&&(r.length>0?r+="/..":r="..",a=2)}else r.length>0?r+="/"+e.slice(u+1,s):r=e.slice(u+1,s),a=s-u-1;u=s,n=0}else c===46&&n!==-1?++n:n=-1}return r}function v(e,t){var r=t.dir||t.root,a=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+a:r+e+a:a}var b={resolve:function(){for(var e="",t=!1,r,a=arguments.length-1;a>=-1&&!t;a--){var u;a>=0?u=arguments[a]:(r===void 0&&(r=process.cwd()),u=r),l(u),u.length!==0&&(e=u+"/"+e,t=u.charCodeAt(0)===47)}return e=g(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(e){if(l(e),e.length===0)return".";var t=e.charCodeAt(0)===47,r=e.charCodeAt(e.length-1)===47;return e=g(e,!t),e.length===0&&!t&&(e="."),e.length>0&&r&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return l(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var r=arguments[t];l(r),r.length>0&&(e===void 0?e=r:e+="/"+r)}return e===void 0?".":b.normalize(e)},relative:function(e,t){if(l(e),l(t),e===t||(e=b.resolve(e),t=b.resolve(t),e===t))return"";for(var r=1;r<e.length&&e.charCodeAt(r)===47;++r);for(var a=e.length,u=a-r,n=1;n<t.length&&t.charCodeAt(n)===47;++n);for(var c=t.length,s=c-n,f=u<s?u:s,p=-1,d=0;d<=f;++d){if(d===f){if(s>f){if(t.charCodeAt(n+d)===47)return t.slice(n+d+1);if(d===0)return t.slice(n+d)}else u>f&&(e.charCodeAt(r+d)===47?p=d:d===0&&(p=0));break}var k=e.charCodeAt(r+d),z=t.charCodeAt(n+d);if(k!==z)break;k===47&&(p=d)}var y="";for(d=r+p+1;d<=a;++d)(d===a||e.charCodeAt(d)===47)&&(y.length===0?y+="..":y+="/..");return y.length>0?y+t.slice(n+p):(n+=p,t.charCodeAt(n)===47&&++n,t.slice(n))},_makeLong:function(e){return e},dirname:function(e){if(l(e),e.length===0)return".";for(var t=e.charCodeAt(0),r=t===47,a=-1,u=!0,n=e.length-1;n>=1;--n)if(t=e.charCodeAt(n),t===47){if(!u){a=n;break}}else u=!1;return a===-1?r?"/":".":r&&a===1?"//":e.slice(0,a)},basename:function(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');l(e);var r=0,a=-1,u=!0,n;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var c=t.length-1,s=-1;for(n=e.length-1;n>=0;--n){var f=e.charCodeAt(n);if(f===47){if(!u){r=n+1;break}}else s===-1&&(u=!1,s=n+1),c>=0&&(f===t.charCodeAt(c)?--c===-1&&(a=n):(c=-1,a=s))}return r===a?a=s:a===-1&&(a=e.length),e.slice(r,a)}else{for(n=e.length-1;n>=0;--n)if(e.charCodeAt(n)===47){if(!u){r=n+1;break}}else a===-1&&(u=!1,a=n+1);return a===-1?"":e.slice(r,a)}},extname:function(e){l(e);for(var t=-1,r=0,a=-1,u=!0,n=0,c=e.length-1;c>=0;--c){var s=e.charCodeAt(c);if(s===47){if(!u){r=c+1;break}continue}a===-1&&(u=!1,a=c+1),s===46?t===-1?t=c:n!==1&&(n=1):t!==-1&&(n=-1)}return t===-1||a===-1||n===0||n===1&&t===a-1&&t===r+1?"":e.slice(t,a)},format:function(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return v("/",e)},parse:function(e){l(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var r=e.charCodeAt(0),a=r===47,u;a?(t.root="/",u=1):u=0;for(var n=-1,c=0,s=-1,f=!0,p=e.length-1,d=0;p>=u;--p){if(r=e.charCodeAt(p),r===47){if(!f){c=p+1;break}continue}s===-1&&(f=!1,s=p+1),r===46?n===-1?n=p:d!==1&&(d=1):n!==-1&&(d=-1)}return n===-1||s===-1||d===0||d===1&&n===s-1&&n===c+1?s!==-1&&(c===0&&a?t.base=t.name=e.slice(1,s):t.base=t.name=e.slice(c,s)):(c===0&&a?(t.name=e.slice(1,n),t.base=e.slice(1,s)):(t.name=e.slice(c,n),t.base=e.slice(c,s)),t.ext=e.slice(n,s)),c>0?t.dir=e.slice(0,c-1):a&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};b.posix=b,i.exports=b}),N=q(F()),m=N,G=N,I=function(o){return o},T=function(){throw new Error("Not implemented")};m.parse??=T;G.parse??=T;var x={resolve:m.resolve.bind(m),normalize:m.normalize.bind(m),isAbsolute:m.isAbsolute.bind(m),join:m.join.bind(m),relative:m.relative.bind(m),toNamespacedPath:I,dirname:m.dirname.bind(m),basename:m.basename.bind(m),extname:m.extname.bind(m),format:m.format.bind(m),parse:m.parse.bind(m),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:I},E={sep:"\\",delimiter:";",win32:void 0,...x,posix:x};x.win32=E.win32=E;x.posix=x;var A=x;var h=[];for(let o=0;o<256;++o)h.push((o+256).toString(16).slice(1));function R(o,i=0){return(h[o[i+0]]+h[o[i+1]]+h[o[i+2]]+h[o[i+3]]+"-"+h[o[i+4]]+h[o[i+5]]+"-"+h[o[i+6]]+h[o[i+7]]+"-"+h[o[i+8]]+h[o[i+9]]+"-"+h[o[i+10]]+h[o[i+11]]+h[o[i+12]]+h[o[i+13]]+h[o[i+14]]+h[o[i+15]]).toLowerCase()}var w,K=new Uint8Array(16);function C(){if(!w){if(typeof crypto==="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");w=crypto.getRandomValues.bind(crypto)}return w(K)}var Q=typeof crypto!=="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),j={randomUUID:Q};function W(o,i,l){if(j.randomUUID&&!i&&!o)return j.randomUUID();o=o||{};let g=o.random??o.rng?.()??C();if(g.length<16)throw new Error("Random bytes length must be >= 16");if(g[6]=g[6]&15|64,g[8]=g[8]&63|128,i){if(l=l||0,l<0||l+16>i.length)throw new RangeError(`UUID byte range ${l}:${l+15} is out of buffer bounds`);for(let v=0;v<16;++v)i[l+v]=g[v];return i}return R(g)}var O=W;var{default:S}=(()=>({}));var V=import.meta.dir,U=A.resolve(V,"../../public/uploaded");if(!S.existsSync(U))S.mkdirSync(U,{recursive:!0});var le=(o={})=>{let i=o.dest?A.resolve(V,o.dest):U;return async(l)=>{try{let g=await l.body;l.req.files??={};for(let v of o?.fields??[]){let b=g[v];if(!b.name)continue;let e=`${v}_${O()}${A.extname(b?.name)}`,t=A.join(i,e);await Bun.write(t,await b.arrayBuffer()),l.req.files[v]=t}}catch(g){return console.error("File upload error:",g),l.json({status:500,message:"Error uploading files"},500)}}};export{le as fileSaveMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function G(q,E){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(B)=>{try{let z=B.cookies?.accessToken??B.req?.headers?.get("Authorization");if(!z)return B.json({message:"Unauthorized",error:"No token provided"},401);if(z.startsWith("Bearer "))z=z.slice(7);let A=q?.verify(z,E);if(!A)return B.json({message:"Unauthorized",error:"Token could not be decoded"},401);B.set("user",A)}catch(z){let A="Invalid token";if(z.name==="TokenExpiredError")A="Token expired";else if(z.name==="JsonWebTokenError")A="Malformed or tampered token";return B.json({message:"Unauthorized",error:A},401)}}}function H(q,E,B){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!E)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(z)=>{try{let A=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!A)return z.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=q?.verify(A,B);if(!C)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let F=await E.findById(C._id).select("-password -refreshToken");if(!F)return z.json({message:"Unauthorized: User not found"},404);z.set("user",F);return}catch(A){let C="Invalid token";if(A.name==="TokenExpiredError")C="Token expired";else if(A.name==="JsonWebTokenError")C="Malformed or tampered token";return z.json({message:"Unauthorized",error:C},401)}}}var L=(q)=>{if(!q.app)throw new Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.jwt)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;let{routes:E,jwt:B,jwtSecret:z}=q,A=G(B,z);return(C)=>{if(!E?.length||E?.includes(C.url.pathname))return A(C)}},N=(q)=>{if(!q.app)throw new Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.userModel)throw new Error("User model is not defined, please provide userModel to authenticateJwt Function");if(!q.jwt)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;let{routes:E,jwt:B,jwtSecret:z,userModel:A}=q,C=H(B,A,z);return(F)=>{if(E?.length===0||E?.includes(F.url.pathname))return C(F)}};export{N as authenticateJwtDB,L as authenticateJwt};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
3
|
-
`)},
|
|
1
|
+
var k={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},N=(A,w,j)=>{let D=k[A]||k.reset,H=j?.method?k.method[j.method]||k.reset:k.reset,I=j?.status?j.status>=500?k.error:j.status>=400?k.warn:k.info:k.reset;console.log(`
|
|
2
|
+
${D}[${A.toUpperCase()}]${k.reset} ${w} - ${H}${j?.method||""}${k.reset}`);let J={timestamp:new Date().toISOString(),...j,status:j?.status?`${I}${j.status}${k.reset}`:void 0,method:j?.method?`${H}${j.method}${k.reset}`:void 0};console.log(JSON.stringify(J,null,2)+`
|
|
3
|
+
`)},U=(A)=>{let{app:w,logger:j,logLevel:D="info",onRequest:H,onSend:I,onError:J,routeNotFound:z}=A||{};w?.addHooks("onRequest",(b,B)=>{b.startTime=Date.now(),j?.()??N(D,"Incoming Request",{method:b.method,url:B.toString(),headers:{"user-agent":b.headers.get("user-agent"),"content-type":b.headers.get("content-type")}}),H?.(b,B)}),w?.addHooks("onSend",async(b)=>{let B=`${Date.now()-b.req.startTime}ms`;j?.()??N(D,"Response Sent",{method:b.req.method,url:b.url.toString(),status:b.status,duration:B,headers:{"content-type":b.headers.get("content-type")}});let G=await I?.(b);if(G instanceof Response)return G}),w?.addHooks("onError",async(b,B,G)=>{j?.()??N("error","Unhandled Error",{method:B.method,url:G.toString(),status:500,error:b.message});let K=await J?.(b,B,G);if(K instanceof Response)return K})},Q=(A,w,j,D=0,H)=>{let I=k.method[w]||k.reset,J=D>=500?k.error:D>=400?k.warn:k.info,z=A==="<--"?`${A} ${I}${w}${k.reset} ${j}`:`${A} ${I}${w}${k.reset} ${j} ${J}${D}${k.reset} ${H||""}`;console.log(z)},T=(A)=>{let w=Date.now()-A;return w<1000?`${w}ms`:`${Math.round(w/1000)}s`},V=(A)=>{let{app:w,log:j,onRequest:D,onSend:H,onError:I,routeNotFound:J}=A;w.addHooks("onRequest",(z,b)=>{z.startTime=Date.now(),j?.()??Q("<--",z.method,b.pathname),D?.(z,b)}),w.addHooks("onSend",async(z)=>{let{method:b,url:B}=z.req,G=new URL(B).pathname;j?.()??Q("-->",b,G,z.status,T(z.req.startTime));let K=await H?.(z);if(K instanceof Response)return K}),w.addHooks("onError",async(z,b,B)=>{j?.()??Q(z.message,b.method,B.toString(),500);let G=await I?.(z,b,B);if(G instanceof Response)return G})};export{V as logger,U as advancedLogger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/types.d.ts
CHANGED
|
@@ -118,7 +118,7 @@ export type corsT = {
|
|
|
118
118
|
optionsSuccessStatus?: number;
|
|
119
119
|
} | null;
|
|
120
120
|
export interface FilterMethods {
|
|
121
|
-
|
|
121
|
+
publicRoutes: (...routes: string[]) => FilterMethods;
|
|
122
122
|
permitAll: () => FilterMethods;
|
|
123
123
|
authenticate: (fnc?: middlewareFunc[]) => Response | Promise<Response | null> | void;
|
|
124
124
|
authenticateJwt: (jwt: any) => Response | Promise<Response | null> | void;
|
package/dist/utils/jwt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function F(
|
|
1
|
+
function F(B,C){if(!B)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let m=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!m)return z.json({message:"Unauthorized",error:"No token provided"},401);if(m.startsWith("Bearer "))m=m.slice(7);let q=B?.verify(m,C);if(!q)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);z.set("user",q)}catch(m){let q="Invalid token";if(m.name==="TokenExpiredError")q="Token expired";else if(m.name==="JsonWebTokenError")q="Malformed or tampered token";return z.json({message:"Unauthorized",error:q},401)}}}function G(B,C,z){if(!B)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!C)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(m)=>{try{let q=m.cookies?.accessToken??m.req?.headers?.get("Authorization");if(!q)return m.json({message:"Unauthorized",error:"No token provided"},401);if(q.startsWith("Bearer "))q=q.slice(7);let A=B?.verify(q,z);if(!A)return m.json({message:"Unauthorized",error:"Token could not be decoded"},401);let E=await C.findById(A._id).select("-password -refreshToken");if(!E)return m.json({message:"Unauthorized: User not found"},404);m.set("user",E);return}catch(q){let A="Invalid token";if(q.name==="TokenExpiredError")A="Token expired";else if(q.name==="JsonWebTokenError")A="Malformed or tampered token";return m.json({message:"Unauthorized",error:A},401)}}}export{F as authenticateJwtMiddleware,G as authenticateJwtDbMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "diesel-core",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"description": "Web framework built on Web Standards",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -40,25 +40,25 @@
|
|
|
40
40
|
"import": "./dist/middlewares/ratelimit/rate-limit.js",
|
|
41
41
|
"require": "./dist/middlewares/ratelimit/rate-limit.js"
|
|
42
42
|
},
|
|
43
|
-
"./redisStore":{
|
|
43
|
+
"./redisStore": {
|
|
44
44
|
"types": "./dist/middlewares/ratelimit/implementation.d.ts",
|
|
45
45
|
"import": "./dist/middlewares/ratelimit/implementation.js",
|
|
46
46
|
"require": "./dist/middlewares/ratelimit/implementation.js"
|
|
47
47
|
},
|
|
48
|
-
"./dicedbStore":{
|
|
48
|
+
"./dicedbStore": {
|
|
49
49
|
"types": "./dist/middlewares/ratelimit/implementation.d.ts",
|
|
50
50
|
"import": "./dist/middlewares/ratelimit/implementation.js",
|
|
51
51
|
"require": "./dist/middlewares/ratelimit/implementation.js"
|
|
52
52
|
},
|
|
53
|
-
"./jwt":{
|
|
53
|
+
"./jwt": {
|
|
54
54
|
"types": "./dist/middlewares/jwt/index.d.ts",
|
|
55
55
|
"import": "./dist/middlewares/jwt/index.js",
|
|
56
|
-
"require": "./dist/middlewares/jwt/index.js"
|
|
56
|
+
"require": "./dist/middlewares/jwt/index.js"
|
|
57
57
|
},
|
|
58
|
-
"./powered-by":{
|
|
58
|
+
"./powered-by": {
|
|
59
59
|
"types": "./dist/middlewares/powered-by/index.d.ts",
|
|
60
60
|
"import": "./dist/middlewares/powered-by/index.js",
|
|
61
|
-
"require": "./dist/middlewares/powered-by/index.js"
|
|
61
|
+
"require": "./dist/middlewares/powered-by/index.js"
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
@@ -96,4 +96,4 @@
|
|
|
96
96
|
"@types/uuid": "^10.0.0",
|
|
97
97
|
"uuid": "^11.1.0"
|
|
98
98
|
}
|
|
99
|
-
}
|
|
99
|
+
}
|
package/dist/routes/hello.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const GET: () => Response;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const GET: () => Response;
|