UNPKG

diesel-core

Version:

Web framework built on Web Standards

2 lines (1 loc) 7.76 kB
var C=Object.create;var{getPrototypeOf:D,defineProperty:E,getOwnPropertyNames:M}=Object;var A=Object.prototype.hasOwnProperty;var F=(L,J,O)=>{O=L!=null?C(D(L)):{};let z=J||!L||!L.__esModule?E(O,"default",{value:L,enumerable:!0}):O;for(let K of M(L))if(!A.call(z,K))E(z,K,{get:()=>L[K],enumerable:!0});return z};var w=((L)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(L,{get:(J,O)=>(typeof require!=="undefined"?require:J)[O]}):L)(function(L){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+L+'" is not supported')});function V(L){switch(L.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function N(L,J,O){let z=null,K=null,X=null,j=null,I={};return{req:L,server:J,url:O,status:200,headers:new Headers,setHeader(G,Y){return this.headers.set(G,Y),this},removeHeader(G){return this.headers.delete(G),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(G){throw new Error("Failed to parse query parameters")}return z},get params(){if(!K&&this.req.routePattern)try{K=b(this.req.routePattern,this.url.pathname)}catch(G){throw new Error("Failed to extract route parameters")}return K??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!j)j=(async()=>{let G=await f(this.req);if(G.error)throw new Error(G.error);return Object.keys(G).length===0?null:G})();return j},set(G,Y){return I[G]=Y,this},get(G){return I[G]},text(G,Y){if(Y)this.status=Y;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(G,{status:this.status,headers:this.headers})},send(G,Y){if(Y)this.status=Y;let $=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),Z;if(G instanceof Uint8Array)Z="Uint8Array";else if(G instanceof ArrayBuffer)Z="ArrayBuffer";else Z=typeof G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",$.get(Z)??"text/plain; charset=utf-8");let U=Z==="object"&&G!==null?JSON.stringify(G):G;return new Response(U,{status:this.status,headers:this.headers})},json(G,Y){if(Y)this.status=Y;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(G,{status:this.status,headers:this.headers})},file(G,Y,$){if($)this.status=$;let Z=Bun.file(G);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Y??V(G));return new Response(Z,{status:this.status,headers:this.headers})},async ejs(G,Y={},$){if($)this.status=$;let Z;try{Z=await import("ejs"),Z=Z.default||Z}catch(U){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 U=await Bun.file(G).text(),g=Z.render(U,Y),B=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(g,{status:this.status,headers:B})}catch(U){return console.error("EJS Rendering Error:",U),new Response("Error rendering template",{status:500})}},redirect(G,Y){if(Y)this.status=Y;else this.status=302;return this.headers.set("Location",G),new Response(null,{status:this.status,headers:this.headers})},stream(G){let Y=new Headers(this.headers),$=new ReadableStream({async start(Z){await G(Z),Z.close()}});return new Response($,{headers:Y})},yieldStream(G){return new Response({async*[Symbol.asyncIterator](){yield*G()}},{headers:this.headers})},setCookie(G,Y,$={}){let Z=`${encodeURIComponent(G)}=${encodeURIComponent(Y)}`;if($.maxAge)Z+=`; Max-Age=${$.maxAge}`;if($.expires)Z+=`; Expires=${$.expires.toUTCString()}`;if($.path)Z+=`; Path=${$.path}`;if($.domain)Z+=`; Domain=${$.domain}`;if($.secure)Z+="; Secure";if($.httpOnly)Z+="; HttpOnly";if($.sameSite)Z+=`; SameSite=${$.sameSite}`;return this.headers.append("Set-Cookie",Z),this},get cookies(){if(!X){let G=this.req.headers.get("cookie");X=G?H(G):{}}return X}}}function H(L){return Object.fromEntries(L.split(";").map((J)=>{let[O,...z]=J.trim().split("=");return[O,decodeURIComponent(z.join("="))]}))}function b(L,J){let O={},z=L.split("/"),[K]=J.split("?"),X=K.split("/");if(z.length!==X.length)return null;for(let j=0;j<z.length;j++)if(z[j].startsWith(":"))O[z[j].slice(1)]=X[j];return O}async function f(L){let J=L.headers.get("Content-Type");if(!J)return{};if(L.headers.get("Content-Length")==="0"||!L.body)return{};try{if(J.startsWith("application/json"))return await L.json();if(J.startsWith("application/x-www-form-urlencoded")){let z=await L.text();return Object.fromEntries(new URLSearchParams(z))}if(J.startsWith("multipart/form-data")){let z=await L.formData(),K={};for(let[X,j]of z.entries())K[X]=j;return K}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}async function S(L,J,O,z){let K=N(L,J,O),X=z.trie.search(O.pathname,L.method);L.routePattern=X?.path;try{if(z.hooks.onRequest)await W("onRequest",z.hooks.onRequest,[L,O,J]);if(z.hasMiddleware){let G=await T(z,O.pathname,K,J);if(G)return G}if(z.hasFilterEnabled){let G=L.routePattern??O.pathname,Y=await P(z,G,K,J);if(Y)return Y}if(!X)return await x(z,K,O.pathname);if(z.hooks.preHandler){let G=await W("preHandler",z.hooks.preHandler,[K,J]);if(G)return G}let j=X.handler(K),I=j instanceof Promise?await j:j;if(z.hasOnSendHook){let G=await W("onSend",z.hooks.onSend,[K,I,J]);if(G)return G}if(I instanceof Response)return I;return _(500,"No response returned from handler.")}catch(j){return await W("onError",z.hooks.onError,[j,L,O,J])||_(500,"Internal Server Error")}}async function W(L,J,O){if(!J?.length)return;for(let z=0;z<J.length;z++){let K=J[z](...O),X=K instanceof Promise?await K:K;if(X&&L!=="onRequest")return X}}async function T(L,J,O,z){if(L.globalMiddlewares.length){let X=await Q(L.globalMiddlewares,O,z);if(X)return X}let K=L.middlewares.get(J)||[];if(K.length){let X=await Q(K,O,z);if(X)return X}return null}async function Q(L,J,O){for(let z of L){let K=await z(J,O);if(K)return K}return null}async function p(L,J,O){for(let z of L){let K=await z(J,O);if(K)return K}}async function P(L,J,O,z){let K=await R(L,J,O,z),X=K instanceof Promise?await K:K;if(X)return X}async function R(L,J,O,z){if(J.endsWith("/"))J=J.slice(0,-1);if(!L.filters.has(J))if(L.filterFunction.length)for(let K of L.filterFunction){let X=await K(O,z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function n(L,J,O,z){if(!L.filters.has(J))if(L.filterFunction.length)for(let K of L.filterFunction){let X=await K(O,z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function x(L,J,O){if(L.staticPath){let K=await q(L,O,J);if(K)return K;let X=L.trie.search("*",J.req.method);if(X?.handler)return await X.handler(J)}return L.routeNotFoundFunc(J)||_(404,`Route not found for ${O}`)}function _(L,J){return new Response(JSON.stringify({error:J}),{status:L,headers:{"Content-Type":"application/json"}})}async function q(L,J,O){if(!L.staticPath)return null;let z=`${L.staticPath}${J}`;if(await Bun.file(z).exists()){let X=V(z);return O.file(z,X,200)}return null}export{q as handleStaticFiles,R as handleFilterRequest,n as handleBunFilterRequest,_ as generateErrorResponse,Q as executeMiddlewares,p as executeBunMiddlewares,S as default};