diesel-core 1.0.0 → 1.0.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/README.md +2 -0
- package/package.json +39 -6
- package/.github/workflows/ci.yml +0 -49
- package/CONTRIBUTING.md +0 -3
- package/build.js +0 -32
- package/dist/PipeLineRequestHandle.d.ts +0 -3
- package/dist/ctx.d.ts +0 -3
- package/dist/ctx.js +0 -1
- package/dist/handleRequest.d.ts +0 -7
- package/dist/handleRequest.js +0 -1
- package/dist/main.d.ts +0 -70
- package/dist/main.js +0 -1
- package/dist/route.d.ts +0 -0
- package/dist/trie.d.ts +0 -31
- package/dist/trie.js +0 -1
- package/dist/types.d.ts +0 -124
- package/dist/utils.d.ts +0 -8
- package/dist/utils.js +0 -1
- package/example/bun.lockb +0 -0
- package/example/main.ts +0 -76
- package/example/package-lock.json +0 -177
- package/example/package.json +0 -21
- package/example/public/assets/ChannelPlayList-p_SqVqPO.js +0 -1
- package/example/public/assets/ChannelPlaylistVideo-5OaiDEnm.js +0 -1
- package/example/public/assets/ChannelSubscribedPage-vSZI2SjA.js +0 -1
- package/example/public/assets/ChannelVideoPage-uDdwQVa6.js +0 -1
- package/example/public/assets/History-vHs9rbHf.js +0 -1
- package/example/public/assets/Home-exHR37S6.js +0 -1
- package/example/public/assets/LikedVideo-pfToIkp3.js +0 -1
- package/example/public/assets/Login-SDitavY0.js +0 -3
- package/example/public/assets/SearchVideoListingPage-mueog3Gj.js +0 -1
- package/example/public/assets/Signup-N_NVHOWz.js +0 -1
- package/example/public/assets/VideoListings-jQdYt2hg.js +0 -1
- package/example/public/assets/Watchpage-sbRLD4ie.js +0 -1
- package/example/public/assets/channelDeatilsPage-bV4pCCm_.js +0 -1
- package/example/public/assets/channelTweets-IfaDjT10.js +0 -1
- package/example/public/assets/index-YCk-SmjN.css +0 -1
- package/example/public/assets/index-g6IK7Mpq.js +0 -854
- package/example/public/assets/subscribeToggle-X_gwL1Mm.js +0 -1
- package/example/public/index.html +0 -14
- package/example/public/vite.svg +0 -1
- package/example/tsconfig.json +0 -16
- package/index.d.ts +0 -5
- package/index.js +0 -9
- package/jsconfig.json +0 -28
- package/make.sh +0 -3
- package/src/PipeLineRequestHandle.ts +0 -73
- package/src/ctx.ts +0 -299
- package/src/handleRequest.ts +0 -175
- package/src/main.ts +0 -497
- package/src/trie.ts +0 -129
- package/src/types.ts +0 -167
- package/src/utils.ts +0 -99
- package/test/index.test.ts +0 -169
- package/test/server.ts +0 -69
- package/tsconfig.json +0 -17
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -1,16 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "diesel-core",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "Web framework built on Web Standards",
|
|
4
5
|
"main": "index.js",
|
|
5
6
|
"types": "index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"./dist"
|
|
9
|
+
],
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/main.d.ts",
|
|
13
|
+
"import": "./dist/main.js",
|
|
14
|
+
"require": "./dist/main.js"
|
|
15
|
+
},
|
|
16
|
+
"./cors": {
|
|
17
|
+
"types": "./dist/middlewares/cors/cors.d.ts",
|
|
18
|
+
"import": "./src/middlewares/cors/cors.js",
|
|
19
|
+
"require": "./dist/middlewares/cors/cors.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
6
22
|
"scripts": {
|
|
7
23
|
"build": "bun run build.js",
|
|
8
|
-
"test": "bun run test
|
|
24
|
+
"test": "bun run test"
|
|
9
25
|
},
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
|
|
26
|
+
"author": "Pradeep Kumar <pradeepbgs62019@gmail.com> (https://github.com/pradeepbgs)",
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"keywords": [
|
|
29
|
+
"diesel",
|
|
30
|
+
"web",
|
|
31
|
+
"app",
|
|
32
|
+
"http",
|
|
33
|
+
"application",
|
|
34
|
+
"framework",
|
|
35
|
+
"router",
|
|
36
|
+
"cloudflare",
|
|
37
|
+
"workers",
|
|
38
|
+
"fastly",
|
|
39
|
+
"compute",
|
|
40
|
+
"deno",
|
|
41
|
+
"bun",
|
|
42
|
+
"lambda",
|
|
43
|
+
"nodejs",
|
|
44
|
+
"bun",
|
|
45
|
+
"bunjs"
|
|
46
|
+
],
|
|
14
47
|
"devDependencies": {
|
|
15
48
|
"@types/bun": "latest"
|
|
16
49
|
},
|
package/.github/workflows/ci.yml
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
name: Ci of Diesel-project
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
pull_request:
|
|
5
|
-
branches:
|
|
6
|
-
- main
|
|
7
|
-
|
|
8
|
-
jobs:
|
|
9
|
-
build:
|
|
10
|
-
name: Build our Diesel-core
|
|
11
|
-
runs-on: ubuntu-latest
|
|
12
|
-
|
|
13
|
-
steps:
|
|
14
|
-
- name: Checkout code
|
|
15
|
-
uses: actions/checkout@v2
|
|
16
|
-
|
|
17
|
-
# Cache Bun installation
|
|
18
|
-
- name: Cache Bun
|
|
19
|
-
id: cache-bun
|
|
20
|
-
uses: actions/cache@v3
|
|
21
|
-
with:
|
|
22
|
-
path: ~/.bun
|
|
23
|
-
key: ${{ runner.os }}-bun-${{ hashFiles('**/bunfig.toml') }}
|
|
24
|
-
restore-keys: |
|
|
25
|
-
${{ runner.os }}-bun-
|
|
26
|
-
|
|
27
|
-
# Install Bun if it's not cached
|
|
28
|
-
- name: Install Bun
|
|
29
|
-
run: |
|
|
30
|
-
if [ ! -d "$HOME/.bun" ]; then
|
|
31
|
-
curl -fsSL https://bun.sh/install | bash
|
|
32
|
-
fi
|
|
33
|
-
echo "$HOME/.bun/bin" >> $GITHUB_PATH
|
|
34
|
-
continue-on-error: true # Allows the workflow to continue even if Bun is already installed
|
|
35
|
-
|
|
36
|
-
- name: Install dependencies
|
|
37
|
-
run: bun install
|
|
38
|
-
|
|
39
|
-
- name: Run TypeScript Compiler
|
|
40
|
-
run: tsc
|
|
41
|
-
|
|
42
|
-
- name: Minify our code
|
|
43
|
-
run: bun run build
|
|
44
|
-
|
|
45
|
-
- name: Run server and Test Application
|
|
46
|
-
env:
|
|
47
|
-
PORT: 3001
|
|
48
|
-
run: bun test
|
|
49
|
-
|
package/CONTRIBUTING.md
DELETED
package/build.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import path from 'path';
|
|
2
|
-
const entryPoints = [
|
|
3
|
-
'./src/main.ts',
|
|
4
|
-
'./src/ctx.ts',
|
|
5
|
-
'./src/handleRequest.ts',
|
|
6
|
-
'./src/trie.ts',
|
|
7
|
-
// './src/router.ts',
|
|
8
|
-
'./src/utils.ts'
|
|
9
|
-
];
|
|
10
|
-
|
|
11
|
-
entryPoints.forEach(entry => {
|
|
12
|
-
console.log(`Building: ${entry}`);
|
|
13
|
-
try {
|
|
14
|
-
Bun.build({
|
|
15
|
-
entrypoints: [path.resolve(entry)],
|
|
16
|
-
outdir: './dist',
|
|
17
|
-
minify: true,
|
|
18
|
-
});
|
|
19
|
-
} catch (error) {
|
|
20
|
-
console.error(`Failed to build ${entry}:`, error);
|
|
21
|
-
}
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
// Bun.spawn(['rm','-rf','./main'])
|
|
25
|
-
|
|
26
|
-
// oha test
|
|
27
|
-
// oha -c 500 -n 100000 -H "Cookie: accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicGsiLCJhZ2UiOjIyLCJpYXQiOjE3Mjk5MjQxOTQsImV4cCI6MTczMDAxMDU5NH0._dEjx5iUuOLoq15-xTPgXOemfzIPrg06Qmruiv-I5cc" http://localhost:3000/
|
|
28
|
-
|
|
29
|
-
// bombardier
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
// bombardier -c 500 -n 100000 -H "Cookie: accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicGsiLCJhZ2UiOjIyLCJpYXQiOjE3Mjk5MjQxOTQsImV4cCI6MTczMDAxMDU5NH0._dEjx5iUuOLoq15-xTPgXOemfzIPrg06Qmruiv-I5cc" http://localhost:3000/
|
package/dist/ctx.d.ts
DELETED
package/dist/ctx.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function D(G){switch(G.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,U,J){let E=new Headers({"X-Powered-By":"DieselJS","Cache-Control":"no-cache"});E.set("X-Powered-By","DieselJS");let Z={},$=!1,X,K=null,O,R,w={};return{req:G,server:U,url:J,setHeader(z,F){return E.set(z,F),this},getUser(){return w},setUser(z){if(z)w=z},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!R)R=await V(G);if(R.error)return new Response(JSON.stringify({error:R.error}),{status:400});return R},set(z,F){if(typeof z!=="string")throw new Error("Key must be string type!");if(!F)throw new Error("value paramter is missing pls pass value after key");return Z[z]=F,this},get(z){return z?Z[z]:null},setAuth(z){return $=z,this},getAuth(){return $},text(z,F){if(!E.has("Content-Type"))E.set("Content-Type","text/plain; charset=utf-8");return new Response(z,{status:F,headers:E})},send(z,F){if(typeof z==="string"){if(!E.has("Content-Type"))E.set("Content-Type","text/plain; charset=utf-8")}else if(typeof z==="object"){if(!E.has("Content-Type"))E.set("Content-Type","application/json; charset=utf-8");z=JSON.stringify(z)}else if(z instanceof Uint8Array||z instanceof ArrayBuffer){if(!E.has("Content-Type"))E.set("Content-Type","application/octet-stream")}return new Response(z,{status:F,headers:E})},json(z,F){if(!E.has("Content-Type"))E.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(z),{status:F,headers:E})},file(z,F=200,L){let Y=D(z),M=Bun.file(z),W=new Headers;if(!W.has("Content-Type"))W.set("Content-Type",L??Y);return new Response(M,{status:F,headers:W})},redirect(z,F){return E.set("Location",z),new Response(null,{status:F??302,headers:E})},setCookie(z,F,L={}){let Y=`${encodeURIComponent(z)}=${encodeURIComponent(F)}`;if(L.maxAge)Y+=`; Max-Age=${L.maxAge}`;if(L.expires)Y+=`; Expires=${L.expires.toUTCString()}`;if(L.path)Y+=`; Path=${L.path}`;if(L.domain)Y+=`; Domain=${L.domain}`;if(L.secure)Y+="; Secure";if(L.httpOnly)Y+="; HttpOnly";if(L.sameSite)Y+=`; SameSite=${L.sameSite}`;return E?.append("Set-Cookie",Y),this},getParams(z){if(!O&&G?.routePattern)O=H(G?.routePattern,J?.pathname);if(z)if(O)return O[z];else return;if(O)return z;else return},getQuery(z){try{if(!X)X=Object.fromEntries(J.searchParams);if(z)return X[z]??void 0;return X}catch(F){return}},getCookie(z){if(!K){let F=G.headers.get("cookie");if(F)K=A(F);else return}if(!K)return;if(z)return K[z]??void 0;else return K}}}function A(G){let U={},J=G?.split(";");for(let E=0;E<J?.length;E++){let[Z,...$]=J[E].trim().split("="),X=$?.join("=").trim();if(Z)U[Z.trim()]=decodeURIComponent(X)}return U}function H(G,U){let J={},E=G.split("/"),[Z]=U.split("?"),$=Z.split("/");if(E.length!==$.length)return null;for(let X=0;X<E.length;X++)if(E[X].startsWith(":"))J[E[X].slice(1)]=$[X];return J}async function V(G){let U=G.headers.get("Content-Type");if(!U)return{};try{if(U.startsWith("application/json"))return await G.json();if(U.startsWith("application/x-www-form-urlencoded")){let J=await G.text();return Object.fromEntries(new URLSearchParams(J))}if(U.startsWith("multipart/form-data")){let J=await G.formData(),E={};for(let[Z,$]of J.entries())E[Z]=$;return E}return{error:"Unknown request body type"}}catch(J){return{error:"Invalid request body format"}}}export{_ as default};
|
package/dist/handleRequest.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { Server } from "bun";
|
|
2
|
-
import type { ContextType, corsT, DieselT } from "./types";
|
|
3
|
-
export default function handleRequest(req: Request, server: Server, url: URL, diesel: DieselT): Promise<Response>;
|
|
4
|
-
export declare function applyCors(req: Request, ctx: ContextType, config?: corsT): Response | null;
|
|
5
|
-
export declare function handleFilterRequest(diesel: DieselT, path: string, ctx: ContextType, server: Server): Promise<Response | undefined>;
|
|
6
|
-
export declare function generateErrorResponse(status: number, message: string): Response;
|
|
7
|
-
export declare function handleStaticFiles(diesel: DieselT, pathname: string, ctx: ContextType): Promise<Response | null>;
|
package/dist/handleRequest.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function A(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 Q(L,J,U){let z=new Headers({"X-Powered-By":"DieselJS","Cache-Control":"no-cache"});z.set("X-Powered-By","DieselJS");let X={},Y=!1,K,Z=null,W,E,F={};return{req:L,server:J,url:U,setHeader(G,$){return z.set(G,$),this},getUser(){return F},setUser(G){if(G)F=G},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!E)E=await M(L);if(E.error)return new Response(JSON.stringify({error:E.error}),{status:400});return E},set(G,$){if(typeof G!=="string")throw new Error("Key must be string type!");if(!$)throw new Error("value paramter is missing pls pass value after key");return X[G]=$,this},get(G){return G?X[G]:null},setAuth(G){return Y=G,this},getAuth(){return Y},text(G,$){if(!z.has("Content-Type"))z.set("Content-Type","text/plain; charset=utf-8");return new Response(G,{status:$,headers:z})},send(G,$){if(typeof G==="string"){if(!z.has("Content-Type"))z.set("Content-Type","text/plain; charset=utf-8")}else if(typeof G==="object"){if(!z.has("Content-Type"))z.set("Content-Type","application/json; charset=utf-8");G=JSON.stringify(G)}else if(G instanceof Uint8Array||G instanceof ArrayBuffer){if(!z.has("Content-Type"))z.set("Content-Type","application/octet-stream")}return new Response(G,{status:$,headers:z})},json(G,$){if(!z.has("Content-Type"))z.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(G),{status:$,headers:z})},file(G,$=200,_){let D=A(G),N=Bun.file(G),j=new Headers;if(!j.has("Content-Type"))j.set("Content-Type",_??D);return new Response(N,{status:$,headers:j})},redirect(G,$){return z.set("Location",G),new Response(null,{status:$??302,headers:z})},setCookie(G,$,_={}){let D=`${encodeURIComponent(G)}=${encodeURIComponent($)}`;if(_.maxAge)D+=`; Max-Age=${_.maxAge}`;if(_.expires)D+=`; Expires=${_.expires.toUTCString()}`;if(_.path)D+=`; Path=${_.path}`;if(_.domain)D+=`; Domain=${_.domain}`;if(_.secure)D+="; Secure";if(_.httpOnly)D+="; HttpOnly";if(_.sameSite)D+=`; SameSite=${_.sameSite}`;return z?.append("Set-Cookie",D),this},getParams(G){if(!W&&L?.routePattern)W=O(L?.routePattern,U?.pathname);if(G)if(W)return W[G];else return;if(W)return G;else return},getQuery(G){try{if(!K)K=Object.fromEntries(U.searchParams);if(G)return K[G]??void 0;return K}catch($){return}},getCookie(G){if(!Z){let $=L.headers.get("cookie");if($)Z=B($);else return}if(!Z)return;if(G)return Z[G]??void 0;else return Z}}}function B(L){let J={},U=L?.split(";");for(let z=0;z<U?.length;z++){let[X,...Y]=U[z].trim().split("="),K=Y?.join("=").trim();if(X)J[X.trim()]=decodeURIComponent(K)}return J}function O(L,J){let U={},z=L.split("/"),[X]=J.split("?"),Y=X.split("/");if(z.length!==Y.length)return null;for(let K=0;K<z.length;K++)if(z[K].startsWith(":"))U[z[K].slice(1)]=Y[K];return U}async function M(L){let J=L.headers.get("Content-Type");if(!J)return{};try{if(J.startsWith("application/json"))return await L.json();if(J.startsWith("application/x-www-form-urlencoded")){let U=await L.text();return Object.fromEntries(new URLSearchParams(U))}if(J.startsWith("multipart/form-data")){let U=await L.formData(),z={};for(let[X,Y]of U.entries())z[X]=Y;return z}return{error:"Unknown request body type"}}catch(U){return{error:"Invalid request body format"}}}async function I(L,J,U,z){let X=z.trie.search(U.pathname,L.method);if(X?.isDynamic)L.routePattern=X.path;let Y=Q(L,J,U);if(z.corsConfig){let Z=C(L,Y,z.corsConfig);if(Z)return Z}if(z.hasOnReqHook&&z.hooks.onRequest)z.hooks.onRequest(L,U,J);if(z.hasFilterEnabled){let Z=L.routePattern??U.pathname,W=await b(z,Z,Y,J);if(W)return W}if(z.hasMiddleware){let Z=z.globalMiddlewares;for(let E=0;E<Z.length;E++){let F=await Z[E](Y,J);if(F)return F}let W=z.middlewares.get(U.pathname)||[];for(let E=0;E<W.length;E++){let F=await W[E](Y,J);if(F)return F}}if(!X||X.method!==L.method){let Z=z.trie.search("*",L.method);if(Z){let W=await T(z,U.pathname,Y);if(W)return W;return await Z.handler(Y)}return V(X?405:404,X?"Method not allowed":`Route not found for ${U.pathname}`)}if(z.hasPreHandlerHook&&z.hooks.preHandler){let Z=await z.hooks.preHandler(Y);if(Z)return Z}let K=await X.handler(Y);if(z.hasPostHandlerHook&&z.hooks.postHandler)await z.hooks.postHandler(Y);if(z.hasOnSendHook&&z.hooks.onSend){let Z=await z.hooks.onSend(Y,K);if(Z)return Z}return K??V(204,"No response from this handler")}function C(L,J,U={}){let z=L.headers.get("origin")??"*",X=U?.origin,Y=U?.allowedHeaders??["Content-Type","Authorization"],K=U?.methods??["GET","POST","PUT","DELETE","OPTIONS"],Z=U?.credentials??!1,W=U?.exposedHeaders??[];if(J.setHeader("Access-Control-Allow-Methods",K),J.setHeader("Access-Control-Allow-Headers",Y),J.setHeader("Access-Control-Allow-Credentials",Z),W.length)J.setHeader("Access-Control-Expose-Headers",W);if(X==="*"||z==="*")J.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(X))if(z&&X.includes(z))J.setHeader("Access-Control-Allow-Origin",z);else if(X.includes("*"))J.setHeader("Access-Control-Allow-Origin","*");else return J.json({message:"CORS not allowed"},403);else if(typeof X==="string")if(z===X)J.setHeader("Access-Control-Allow-Origin",z);else return J.json({message:"CORS not allowed"},403);else return J.json({message:"CORS not allowed"},403);if(J.setHeader("Access-Control-Allow-Origin",z),L.method==="OPTIONS")return J.setHeader("Access-Control-Max-Age","86400"),J.text("",204);return null}async function b(L,J,U,z){if(!L.filters.has(J)){if(L.filterFunction.length)for(let X of L.filterFunction){let Y=await X(U,z);if(Y)return Y}return U.json({error:!0,message:"Protected route, authentication required",status:401},401)}}function V(L,J){return new Response(JSON.stringify({error:!0,message:J,status:L}),{status:L,headers:{"Content-Type":"application/json"}})}async function T(L,J,U){if(!L.staticFiles)throw new Error("Static files directory is not configured.");let z=`${L.staticFiles}${J}`;if(/\.(js|css|html)$/.test(J)){let X=A(z);return U.file(z,200,X)}return null}export{T as handleStaticFiles,b as handleFilterRequest,V as generateErrorResponse,I as default,C as applyCors};
|
package/dist/main.d.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import Trie from "./trie.js";
|
|
2
|
-
import { corsT, FilterMethods, HookFunction, HookType, listenArgsT, middlewareFunc, onError, onRequest, type handlerFunction, type Hooks } from "./types.js";
|
|
3
|
-
import { Server } from "bun";
|
|
4
|
-
export default class Diesel {
|
|
5
|
-
private tempRoutes;
|
|
6
|
-
globalMiddlewares: middlewareFunc[];
|
|
7
|
-
middlewares: Map<string, middlewareFunc[]>;
|
|
8
|
-
trie: Trie;
|
|
9
|
-
hasOnReqHook: boolean;
|
|
10
|
-
hasMiddleware: boolean;
|
|
11
|
-
hasPreHandlerHook: boolean;
|
|
12
|
-
hasPostHandlerHook: boolean;
|
|
13
|
-
hasOnSendHook: boolean;
|
|
14
|
-
hasOnError: boolean;
|
|
15
|
-
hooks: Hooks;
|
|
16
|
-
corsConfig: corsT;
|
|
17
|
-
FilterRoutes: string[] | null | undefined;
|
|
18
|
-
filters: Set<string>;
|
|
19
|
-
filterFunction: middlewareFunc[];
|
|
20
|
-
hasFilterEnabled: boolean;
|
|
21
|
-
private serverInstance;
|
|
22
|
-
staticFiles: any;
|
|
23
|
-
constructor();
|
|
24
|
-
setupFilter(): FilterMethods;
|
|
25
|
-
cors(corsConfig: corsT): this;
|
|
26
|
-
static(filePath: string): void;
|
|
27
|
-
addHooks(typeOfHook: HookType, fnc: HookFunction | onError | onRequest): this;
|
|
28
|
-
private compile;
|
|
29
|
-
listen(port?: number, ...args: listenArgsT[]): Server | void;
|
|
30
|
-
close(): void;
|
|
31
|
-
/**
|
|
32
|
-
* Registers a router instance for subrouting.
|
|
33
|
-
* Allows defining subroutes like:
|
|
34
|
-
* const userRoute = new Diesel();
|
|
35
|
-
* app.route("/api/v1/user", userRoute);
|
|
36
|
-
*/
|
|
37
|
-
route(basePath: string, routerInstance: any): this;
|
|
38
|
-
/**
|
|
39
|
-
* Registers a router instance for subrouting.
|
|
40
|
-
* Allows defining subroutes like:
|
|
41
|
-
* const userRoute = new Diesel();
|
|
42
|
-
* userRoute.post("/login",handlerFunction)
|
|
43
|
-
* userRoute.post("/register", handlerFunction)
|
|
44
|
-
* app.register("/api/v1/user", userRoute);
|
|
45
|
-
*/
|
|
46
|
-
register(basePath: string, routerInstance: any): this;
|
|
47
|
-
private addRoute;
|
|
48
|
-
/**
|
|
49
|
-
* Adds middleware to the application.
|
|
50
|
-
* - Middlewares are executed in the order they are added.
|
|
51
|
-
* - Duplicate middleware functions will run multiple times if explicitly included.
|
|
52
|
-
*
|
|
53
|
-
* Examples:
|
|
54
|
-
* - app.use(h1) -> Adds a single global middleware.
|
|
55
|
-
* - app.use([h1, h2]) -> Adds multiple global middlewares.
|
|
56
|
-
* - app.use("/home", h1) -> Adds `h1` middleware to the `/home` path.
|
|
57
|
-
* - app.use(["/home", "/user"], [h1, h2]) -> Adds `h1` and `h2` to `/home` and `/user`.
|
|
58
|
-
* - app.use(h1, [h2, h1]) -> Runs `h1`, then `h2`, and `h1` again as specified.
|
|
59
|
-
*/
|
|
60
|
-
use(pathORHandler?: string | string[] | middlewareFunc | middlewareFunc[], handlers?: middlewareFunc | middlewareFunc[]): this | void;
|
|
61
|
-
get(path: string, ...handlers: handlerFunction[]): this;
|
|
62
|
-
post(path: string, ...handlers: handlerFunction[]): this;
|
|
63
|
-
put(path: string, ...handlers: handlerFunction[]): this;
|
|
64
|
-
patch(path: string, ...handlers: handlerFunction[]): this;
|
|
65
|
-
delete(path: string, ...handlers: handlerFunction[]): this;
|
|
66
|
-
any(path: string, ...handlers: handlerFunction[]): this;
|
|
67
|
-
head(path: string, ...handlers: handlerFunction[]): this;
|
|
68
|
-
options(path: string, ...handlers: handlerFunction[]): this;
|
|
69
|
-
propfind(path: string, ...handlers: handlerFunction[]): this;
|
|
70
|
-
}
|
package/dist/main.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
class B{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class D{root;constructor(){this.root=new B}insert(z,G){let L=this.root,J=z.split("/").filter(Boolean);if(z==="/"){L.isEndOfWord=!0,L.handler.push(G.handler),L.path=z,L.method.push(G.method);return}for(let U of J){let X=!1,Y=U;if(U.startsWith(":"))X=!0,Y=":";if(!L.children[Y])L.children[Y]=new B;L=L.children[Y],L.isDynamic=X,L.pattern=U,L.method.push(G.method),L.handler.push(G.handler),L.path=z}L.isEndOfWord=!0,L.method.push(G.method),L.handler.push(G.handler),L.path=z}search(z,G){let L=this.root,J=z.split("/").filter(Boolean),U=J.length;for(let $ of J){let K=$;if(!L.children[K])if(L.children[":"])L=L.children[":"];else return null;else L=L.children[K]}let X=L.path.split("/").filter(Boolean);if(U!==X.length)return null;let Y=L.method.indexOf(G);if(Y!==-1)return{path:L.path,handler:L.handler[Y],isDynamic:L.isDynamic,pattern:L.pattern,method:L.method[Y]};return{path:L.path,handler:L.handler,isDynamic:L.isDynamic,pattern:L.pattern,method:L.method[Y]}}}function Q(z){switch(z.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}function j(z,G,L){let J=new Headers({"X-Powered-By":"DieselJS","Cache-Control":"no-cache"});J.set("X-Powered-By","DieselJS");let U={},X=!1,Y,$=null,K,E,A={};return{req:z,server:G,url:L,setHeader(Z,W){return J.set(Z,W),this},getUser(){return A},setUser(Z){if(Z)A=Z},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!E)E=await S(z);if(E.error)return new Response(JSON.stringify({error:E.error}),{status:400});return E},set(Z,W){if(typeof Z!=="string")throw new Error("Key must be string type!");if(!W)throw new Error("value paramter is missing pls pass value after key");return U[Z]=W,this},get(Z){return Z?U[Z]:null},setAuth(Z){return X=Z,this},getAuth(){return X},text(Z,W){if(!J.has("Content-Type"))J.set("Content-Type","text/plain; charset=utf-8");return new Response(Z,{status:W,headers:J})},send(Z,W){if(typeof Z==="string"){if(!J.has("Content-Type"))J.set("Content-Type","text/plain; charset=utf-8")}else if(typeof Z==="object"){if(!J.has("Content-Type"))J.set("Content-Type","application/json; charset=utf-8");Z=JSON.stringify(Z)}else if(Z instanceof Uint8Array||Z instanceof ArrayBuffer){if(!J.has("Content-Type"))J.set("Content-Type","application/octet-stream")}return new Response(Z,{status:W,headers:J})},json(Z,W){if(!J.has("Content-Type"))J.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(Z),{status:W,headers:J})},file(Z,W=200,_){let F=Q(Z),T=Bun.file(Z),V=new Headers;if(!V.has("Content-Type"))V.set("Content-Type",_??F);return new Response(T,{status:W,headers:V})},redirect(Z,W){return J.set("Location",Z),new Response(null,{status:W??302,headers:J})},setCookie(Z,W,_={}){let F=`${encodeURIComponent(Z)}=${encodeURIComponent(W)}`;if(_.maxAge)F+=`; Max-Age=${_.maxAge}`;if(_.expires)F+=`; Expires=${_.expires.toUTCString()}`;if(_.path)F+=`; Path=${_.path}`;if(_.domain)F+=`; Domain=${_.domain}`;if(_.secure)F+="; Secure";if(_.httpOnly)F+="; HttpOnly";if(_.sameSite)F+=`; SameSite=${_.sameSite}`;return J?.append("Set-Cookie",F),this},getParams(Z){if(!K&&z?.routePattern)K=b(z?.routePattern,L?.pathname);if(Z)if(K)return K[Z];else return;if(K)return Z;else return},getQuery(Z){try{if(!Y)Y=Object.fromEntries(L.searchParams);if(Z)return Y[Z]??void 0;return Y}catch(W){return}},getCookie(Z){if(!$){let W=z.headers.get("cookie");if(W)$=I(W);else return}if(!$)return;if(Z)return $[Z]??void 0;else return $}}}function I(z){let G={},L=z?.split(";");for(let J=0;J<L?.length;J++){let[U,...X]=L[J].trim().split("="),Y=X?.join("=").trim();if(U)G[U.trim()]=decodeURIComponent(Y)}return G}function b(z,G){let L={},J=z.split("/"),[U]=G.split("?"),X=U.split("/");if(J.length!==X.length)return null;for(let Y=0;Y<J.length;Y++)if(J[Y].startsWith(":"))L[J[Y].slice(1)]=X[Y];return L}async function S(z){let G=z.headers.get("Content-Type");if(!G)return{};try{if(G.startsWith("application/json"))return await z.json();if(G.startsWith("application/x-www-form-urlencoded")){let L=await z.text();return Object.fromEntries(new URLSearchParams(L))}if(G.startsWith("multipart/form-data")){let L=await z.formData(),J={};for(let[U,X]of L.entries())J[U]=X;return J}return{error:"Unknown request body type"}}catch(L){return{error:"Invalid request body format"}}}async function N(z,G,L,J){let U=J.trie.search(L.pathname,z.method);if(U?.isDynamic)z.routePattern=U.path;let X=j(z,G,L);if(J.corsConfig){let $=w(z,X,J.corsConfig);if($)return $}if(J.hasOnReqHook&&J.hooks.onRequest)J.hooks.onRequest(z,L,G);if(J.hasFilterEnabled){let $=z.routePattern??L.pathname,K=await v(J,$,X,G);if(K)return K}if(J.hasMiddleware){let $=J.globalMiddlewares;for(let E=0;E<$.length;E++){let A=await $[E](X,G);if(A)return A}let K=J.middlewares.get(L.pathname)||[];for(let E=0;E<K.length;E++){let A=await K[E](X,G);if(A)return A}}if(!U||U.method!==z.method){let $=J.trie.search("*",z.method);if($){let K=await O(J,L.pathname,X);if(K)return K;return await $.handler(X)}return C(U?405:404,U?"Method not allowed":`Route not found for ${L.pathname}`)}if(J.hasPreHandlerHook&&J.hooks.preHandler){let $=await J.hooks.preHandler(X);if($)return $}let Y=await U.handler(X);if(J.hasPostHandlerHook&&J.hooks.postHandler)await J.hooks.postHandler(X);if(J.hasOnSendHook&&J.hooks.onSend){let $=await J.hooks.onSend(X,Y);if($)return $}return Y??C(204,"No response from this handler")}function w(z,G,L={}){let J=z.headers.get("origin")??"*",U=L?.origin,X=L?.allowedHeaders??["Content-Type","Authorization"],Y=L?.methods??["GET","POST","PUT","DELETE","OPTIONS"],$=L?.credentials??!1,K=L?.exposedHeaders??[];if(G.setHeader("Access-Control-Allow-Methods",Y),G.setHeader("Access-Control-Allow-Headers",X),G.setHeader("Access-Control-Allow-Credentials",$),K.length)G.setHeader("Access-Control-Expose-Headers",K);if(U==="*"||J==="*")G.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(U))if(J&&U.includes(J))G.setHeader("Access-Control-Allow-Origin",J);else if(U.includes("*"))G.setHeader("Access-Control-Allow-Origin","*");else return G.json({message:"CORS not allowed"},403);else if(typeof U==="string")if(J===U)G.setHeader("Access-Control-Allow-Origin",J);else return G.json({message:"CORS not allowed"},403);else return G.json({message:"CORS not allowed"},403);if(G.setHeader("Access-Control-Allow-Origin",J),z.method==="OPTIONS")return G.setHeader("Access-Control-Max-Age","86400"),G.text("",204);return null}async function v(z,G,L,J){if(!z.filters.has(G)){if(z.filterFunction.length)for(let U of z.filterFunction){let X=await U(L,J);if(X)return X}return L.json({error:!0,message:"Protected route, authentication required",status:401},401)}}function C(z,G){return new Response(JSON.stringify({error:!0,message:G,status:z}),{status:z,headers:{"Content-Type":"application/json"}})}async function O(z,G,L){if(!z.staticFiles)throw new Error("Static files directory is not configured.");let J=`${z.staticFiles}${G}`;if(/\.(js|css|html)$/.test(G)){let U=Q(J);return L.file(J,200,U)}return null}class M{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;constructor(){this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new D,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticFiles=null}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...z)=>{return this.FilterRoutes=z,this.setupFilter()},permitAll:()=>{for(let z of this?.FilterRoutes)this.filters.add(z);return this.FilterRoutes=null,this.setupFilter()},authenticate:(z)=>{if(z?.length)for(let G of z)this.filterFunction.push(G)}}}cors(z){return this.corsConfig=z,this}static(z){this.staticFiles=z}addHooks(z,G){if(typeof z!=="string")throw new Error("hookName must be a string");if(typeof G!=="function")throw new Error("callback must be a instance of function");switch(z){case"onRequest":this.hooks.onRequest=G,this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler=G,this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler=G,this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend=G,this.hasOnSendHook=!0;break;case"onError":this.hooks.onError=G,this.hasOnError=!0;break;case"onClose":this.hooks.onClose=G;break;default:throw new Error(`Unknown hook type: ${z}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[z,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;if(this.hooks.onError)this.hasOnError=!0;this.tempRoutes=new Map}listen(z=3000,...G){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(!z||typeof z!=="number")throw new Error("port is required and should be a number type");let L="0.0.0.0",J=void 0,U={};for(let Y of G)if(typeof Y==="string")L=Y;else if(typeof Y==="function")J=Y;else if(typeof Y==="object"&&Y!==null)U=Y;let X={port:z,hostname:L,fetch:async(Y,$)=>{let K=new URL(Y.url);try{return await N(Y,$,K,this)}catch(E){return this.hasOnError&&this.hooks.onError?this.hooks.onError(E,Y,K,$):new Response(JSON.stringify({message:"Internal Server Error",error:E.message,status:500}),{status:500})}}};if(U.sslCert&&U.sslKey)X.certFile=U.sslCert,X.keyFile=U.sslKey;if(this.compile(),this.serverInstance=Bun?.serve(X),J)return J();if(U.sslCert&&U.sslKey)console.log(`HTTPS server is running on https://localhost:${z}`);else console.log(`HTTP server is running on http://localhost:${z}`);return this.serverInstance}close(){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,console.log("Server has been stopped.");else console.warn("Server is not running.")}route(z,G){if(!z||typeof z!=="string")throw new Error("Path must be a string");let L=Object.fromEntries(G.tempRoutes);return Object.entries(L).forEach(([U,X])=>{let Y=`${z}${U}`;if(!this.middlewares.has(Y))this.middlewares.set(Y,[]);X.handlers.slice(0,-1).forEach((A)=>{if(!this.middlewares.get(Y)?.includes(A))this.middlewares.get(Y)?.push(A)});let K=X.handlers[X.handlers.length-1],E=X.method;try{this.trie.insert(Y,{handler:K,method:E})}catch(A){console.error(`Error inserting ${Y}:`,A)}}),G=null,this}register(z,G){return this.route(z,G)}addRoute(z,G,L){if(typeof G!=="string")throw new Error(`Error in ${L[L.length-1]}: Path must be a string. Received: ${typeof G}`);if(typeof z!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof z}`);this.tempRoutes.set(G,{method:z,handlers:L});let J=L.slice(0,-1),U=L[L.length-1];if(!this.middlewares.has(G))this.middlewares.set(G,[]);J.forEach((X)=>{if(G==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...J])];else if(!this.middlewares.get(G)?.includes(X))this.middlewares.get(G)?.push(X)});try{if(z==="ANY"){let X=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let Y of X)this.trie.insert(G,{handler:U,method:Y})}this.trie.insert(G,{handler:U,method:z})}catch(X){console.error(`Error inserting ${G}:`,X)}}use(z,G){if(Array.isArray(z))z.forEach((J)=>{if(typeof J==="function")this.globalMiddlewares.push(J)});if(typeof z==="function"){if(this.globalMiddlewares.push(z),Array.isArray(G))G.forEach((J)=>{this.globalMiddlewares.push(J)});return}return(Array.isArray(z)?z.filter((J)=>typeof J==="string"):[z].filter((J)=>typeof J==="string")).forEach((J)=>{if(!this.middlewares.has(J))this.middlewares.set(J,[]);if(G)(Array.isArray(G)?G:[G]).forEach((X)=>{this.middlewares.get(J)?.push(X)})}),this}get(z,...G){return this.addRoute("GET",z,G),this}post(z,...G){return this.addRoute("POST",z,G),this}put(z,...G){return this.addRoute("PUT",z,G),this}patch(z,...G){return this.addRoute("PATCH",z,G),this}delete(z,...G){return this.addRoute("DELETE",z,G),this}any(z,...G){return this.addRoute("ANY",z,G),this}head(z,...G){return this.addRoute("HEAD",z,G),this}options(z,...G){return this.addRoute("OPTIONS",z,G),this}propfind(z,...G){return this.addRoute("PROPFIND",z,G),this}}export{M as default};
|
package/dist/route.d.ts
DELETED
|
File without changes
|
package/dist/trie.d.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import type { handlerFunction, HttpMethod, RouteT } from "./types";
|
|
2
|
-
declare class TrieNode {
|
|
3
|
-
children: Record<string, TrieNode>;
|
|
4
|
-
isEndOfWord: boolean;
|
|
5
|
-
handler: handlerFunction[];
|
|
6
|
-
isDynamic: boolean;
|
|
7
|
-
pattern: string;
|
|
8
|
-
path: string;
|
|
9
|
-
method: string[];
|
|
10
|
-
subMiddlewares: Map<string, handlerFunction[]>;
|
|
11
|
-
constructor();
|
|
12
|
-
}
|
|
13
|
-
export default class Trie {
|
|
14
|
-
root: TrieNode;
|
|
15
|
-
constructor();
|
|
16
|
-
insert(path: string, route: RouteT): void;
|
|
17
|
-
search(path: string, method: HttpMethod): {
|
|
18
|
-
path: string;
|
|
19
|
-
handler: handlerFunction;
|
|
20
|
-
isDynamic: boolean;
|
|
21
|
-
pattern: string;
|
|
22
|
-
method: string;
|
|
23
|
-
} | {
|
|
24
|
-
path: string;
|
|
25
|
-
handler: handlerFunction[];
|
|
26
|
-
isDynamic: boolean;
|
|
27
|
-
pattern: string;
|
|
28
|
-
method: string;
|
|
29
|
-
} | null;
|
|
30
|
-
}
|
|
31
|
-
export {};
|
package/dist/trie.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
class E{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class G{root;constructor(){this.root=new E}insert(w,v){let j=this.root,A=w.split("/").filter(Boolean);if(w==="/"){j.isEndOfWord=!0,j.handler.push(v.handler),j.path=w,j.method.push(v.method);return}for(let z of A){let B=!1,q=z;if(z.startsWith(":"))B=!0,q=":";if(!j.children[q])j.children[q]=new E;j=j.children[q],j.isDynamic=B,j.pattern=z,j.method.push(v.method),j.handler.push(v.handler),j.path=w}j.isEndOfWord=!0,j.method.push(v.method),j.handler.push(v.handler),j.path=w}search(w,v){let j=this.root,A=w.split("/").filter(Boolean),z=A.length;for(let H of A){let F=H;if(!j.children[F])if(j.children[":"])j=j.children[":"];else return null;else j=j.children[F]}let B=j.path.split("/").filter(Boolean);if(z!==B.length)return null;let q=j.method.indexOf(v);if(q!==-1)return{path:j.path,handler:j.handler[q],isDynamic:j.isDynamic,pattern:j.pattern,method:j.method[q]};return{path:j.path,handler:j.handler,isDynamic:j.isDynamic,pattern:j.pattern,method:j.method[q]}}}export{G as default};
|
package/dist/types.d.ts
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import { Server } from "bun";
|
|
2
|
-
export type listenCalllBackType = () => void;
|
|
3
|
-
export type handlerFunction = (ctx: ContextType, server?: Server) => Response | Promise<Response | null | void>;
|
|
4
|
-
export type middlewareFunc = (ctx: ContextType, server?: Server | undefined) => null | void | Response | Promise<Response | void | null>;
|
|
5
|
-
export type HookFunction = (ctx: ContextType, result?: Response | null | void, server?: Server) => Response | Promise<Response | null | void> | void;
|
|
6
|
-
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD" | "ANY" | "PROPFIND";
|
|
7
|
-
export type HookType = 'onRequest' | 'preHandler' | 'postHandler' | 'onSend' | 'onError' | 'onClose';
|
|
8
|
-
export interface onError {
|
|
9
|
-
(error: Error, req: Request, url: URL, server: Server): void | null | Response | Promise<Response | null | void>;
|
|
10
|
-
}
|
|
11
|
-
export interface onRequest {
|
|
12
|
-
(req: Request, url: URL, server: Server): void | null | Response | Promise<Response | null | void>;
|
|
13
|
-
}
|
|
14
|
-
export interface Hooks {
|
|
15
|
-
onRequest: onRequest | null;
|
|
16
|
-
preHandler: HookFunction | null;
|
|
17
|
-
postHandler: HookFunction | null;
|
|
18
|
-
onSend: HookFunction | null;
|
|
19
|
-
onError: onError | null;
|
|
20
|
-
onClose: HookFunction | null;
|
|
21
|
-
}
|
|
22
|
-
export interface ContextType {
|
|
23
|
-
req: Request;
|
|
24
|
-
server: Server;
|
|
25
|
-
url: URL;
|
|
26
|
-
setUser: (data?: any) => void;
|
|
27
|
-
getUser: () => any;
|
|
28
|
-
getIP: () => any;
|
|
29
|
-
getBody: () => Promise<any>;
|
|
30
|
-
setHeader: (key: string, value: any) => this;
|
|
31
|
-
set: (key: string, value: any) => this;
|
|
32
|
-
get: (key: string) => any;
|
|
33
|
-
setAuth: (authStatus: boolean) => this;
|
|
34
|
-
getAuth: () => boolean;
|
|
35
|
-
json: (data: Object, status?: number) => Response;
|
|
36
|
-
text: (data: string, status?: number) => Response;
|
|
37
|
-
send: (data: string, status?: number) => Response;
|
|
38
|
-
file: (filePath: string, status?: number, mimeType?: string) => Response;
|
|
39
|
-
redirect: (path: string, status?: number) => Response;
|
|
40
|
-
getParams: (props?: any) => any;
|
|
41
|
-
getQuery: (props?: any) => any;
|
|
42
|
-
setCookie: (name: string, value: string, options?: CookieOptions) => this;
|
|
43
|
-
getCookie: (cookieName?: string) => any;
|
|
44
|
-
}
|
|
45
|
-
export interface CookieOptions {
|
|
46
|
-
maxAge?: number;
|
|
47
|
-
expires?: Date;
|
|
48
|
-
path?: string;
|
|
49
|
-
domain?: string;
|
|
50
|
-
secure?: boolean;
|
|
51
|
-
httpOnly?: boolean;
|
|
52
|
-
sameSite?: "Strict" | "Lax" | "None";
|
|
53
|
-
}
|
|
54
|
-
export interface RouteNodeType {
|
|
55
|
-
path: string;
|
|
56
|
-
handler: Function[];
|
|
57
|
-
method: string[];
|
|
58
|
-
}
|
|
59
|
-
export interface RouteHandlerT {
|
|
60
|
-
method: string;
|
|
61
|
-
handler: (ctx: ContextType) => Promise<Response | null | void>;
|
|
62
|
-
isDynamic?: boolean;
|
|
63
|
-
path?: string;
|
|
64
|
-
}
|
|
65
|
-
export interface DieselT {
|
|
66
|
-
hasOnReqHook: boolean;
|
|
67
|
-
hasMiddleware: boolean;
|
|
68
|
-
hasPreHandlerHook: boolean;
|
|
69
|
-
hasPostHandlerHook: boolean;
|
|
70
|
-
hasOnSendHook: boolean;
|
|
71
|
-
hooks: {
|
|
72
|
-
onRequest: ((req: Request, url: URL, serer: Server) => void) | null;
|
|
73
|
-
preHandler: ((ctx: ContextType, serer?: Server) => Response | Promise<Response | void | null>) | null;
|
|
74
|
-
postHandler: ((ctx: ContextType, serer?: Server) => Response | Promise<Response | void | null>) | null;
|
|
75
|
-
onSend: ((ctx?: ContextType, result?: Response | null | void, serer?: Server) => Response | Promise<Response | void | null>) | null;
|
|
76
|
-
onError: ((error: Error, req: Request, url: URL, server?: Server) => void | Response | Promise<Response | null | void>) | null;
|
|
77
|
-
};
|
|
78
|
-
filters: Set<string>;
|
|
79
|
-
hasFilterEnabled: boolean;
|
|
80
|
-
filterFunction: Array<(ctx: ContextType, serer?: Server) => void | Response | Promise<Response | void | null>>;
|
|
81
|
-
corsConfig: corsT | null;
|
|
82
|
-
globalMiddlewares: Array<(ctx: ContextType, serer?: Server) => void | Promise<Response | null | void>>;
|
|
83
|
-
middlewares: Map<string, Array<(ctx: ContextType, serer?: Server) => void | Promise<Response | null | void>>>;
|
|
84
|
-
trie: {
|
|
85
|
-
search: (pathname: string, method: string) => RouteHandlerT | undefined;
|
|
86
|
-
};
|
|
87
|
-
staticFiles: string | null;
|
|
88
|
-
}
|
|
89
|
-
export interface RouteCache {
|
|
90
|
-
[key: string]: RouteHandlerT | undefined;
|
|
91
|
-
}
|
|
92
|
-
declare global {
|
|
93
|
-
interface Request {
|
|
94
|
-
routePattern?: string;
|
|
95
|
-
[key: string]: any;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
export interface ParseBodyResult {
|
|
99
|
-
error?: string;
|
|
100
|
-
data?: any;
|
|
101
|
-
}
|
|
102
|
-
export interface RouteT {
|
|
103
|
-
method: string;
|
|
104
|
-
handler: handlerFunction;
|
|
105
|
-
}
|
|
106
|
-
export type corsT = {
|
|
107
|
-
origin?: string | string[] | null;
|
|
108
|
-
methods?: string | string[] | null;
|
|
109
|
-
allowedHeaders?: string | string[] | null;
|
|
110
|
-
exposedHeaders?: string | string[] | null;
|
|
111
|
-
credentials?: boolean | null;
|
|
112
|
-
maxAge?: number;
|
|
113
|
-
preflightContinue?: boolean;
|
|
114
|
-
optionsSuccessStatus?: number;
|
|
115
|
-
} | null;
|
|
116
|
-
export interface FilterMethods {
|
|
117
|
-
routeMatcher: (...routes: string[]) => FilterMethods;
|
|
118
|
-
permitAll: () => FilterMethods;
|
|
119
|
-
authenticate: (fnc?: middlewareFunc[]) => Response | Promise<Response | null> | void;
|
|
120
|
-
}
|
|
121
|
-
export type listenArgsT = string | (() => void) | {
|
|
122
|
-
sslCert?: string;
|
|
123
|
-
sslKey?: string;
|
|
124
|
-
};
|
package/dist/utils.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { ContextType } from "./types";
|
|
2
|
-
export default function rateLimit(props: {
|
|
3
|
-
time?: number;
|
|
4
|
-
max?: number;
|
|
5
|
-
message?: string;
|
|
6
|
-
}): (ctx: ContextType) => void | Response;
|
|
7
|
-
export declare function getMimeType(filePath: string): string;
|
|
8
|
-
export declare const binaryS: (arr: string[], target: string, start: number, end: number) => boolean;
|
package/dist/utils.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function J(j){let{time:z=60000,max:C=100,message:D="Rate limit exceeded. Please try again later."}=j,v=new Map;return(G)=>{let E=new Date,F=G.getIP().address;if(!v.has(F))v.set(F,{count:0,startTime:E});let A=v.get(F);if(A)if(E-A.startTime>z)A.count=1,A.startTime=E;else A.count++;if(A&&A.count>C)return G.json({error:D},429)}}function K(j){switch(j.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"}}var H=(j,z,C,D)=>{if(C>D)return!1;let v=C+(D-C)/2;if(j[v]==z)return!0;if(j[v]>z)return H(j,z,C,v-1);return H(j,z,v+1,D)};export{K as getMimeType,J as default,H as binaryS};
|
package/example/bun.lockb
DELETED
|
Binary file
|
package/example/main.ts
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import Diesel from "../src/main";
|
|
2
|
-
import jwt from "jsonwebtoken";
|
|
3
|
-
import { ContextType, CookieOptions, middlewareFunc } from "../src/types";
|
|
4
|
-
import { newRoute, userRoute } from "./route";
|
|
5
|
-
|
|
6
|
-
const app = new Diesel();
|
|
7
|
-
const SECRET_KEY = "linux";
|
|
8
|
-
const port = 3000
|
|
9
|
-
|
|
10
|
-
// app.cors({
|
|
11
|
-
// origin: "http://localhost:3000",
|
|
12
|
-
// methods: ["GET", "POST", "PUT", "DELETE"],
|
|
13
|
-
// allowedHeaders: ["Content-Type", "Authorization"],
|
|
14
|
-
// credentials: true,
|
|
15
|
-
// });
|
|
16
|
-
|
|
17
|
-
// Authentication Middleware
|
|
18
|
-
export async function authJwt(ctx: ContextType): Promise<void | null | Response> {
|
|
19
|
-
const token = ctx.getCookie("accessToken");
|
|
20
|
-
if (!token) {
|
|
21
|
-
return ctx.json({ message: "Authentication token missing" },401);
|
|
22
|
-
}
|
|
23
|
-
try {
|
|
24
|
-
const user = jwt.verify(token, SECRET_KEY);
|
|
25
|
-
ctx.setUser(user);
|
|
26
|
-
} catch (error) {
|
|
27
|
-
return ctx.json({ message: "Invalid token" },403);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
app
|
|
34
|
-
.static(`${import.meta.dir}/public`)
|
|
35
|
-
|
|
36
|
-
// app.setupFilter()
|
|
37
|
-
// .routeMatcher("/cookie").permitAll()
|
|
38
|
-
// .authenticate([authJwt]);
|
|
39
|
-
|
|
40
|
-
// Error Handling Hook
|
|
41
|
-
app.addHooks("onError", (error: any, req: Request, url: URL) => {
|
|
42
|
-
console.error(`Error occurred: ${error.message}`);
|
|
43
|
-
console.error(`Request Method: ${req.method}, Request URL: ${url}`);
|
|
44
|
-
return new Response("Internal Server Error", { status: 500 });
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
// Routes
|
|
49
|
-
|
|
50
|
-
app
|
|
51
|
-
// .get("*",async (ctx:ContextType) => {
|
|
52
|
-
// return ctx.file(`${import.meta.dir}/public/index.html`)
|
|
53
|
-
// })
|
|
54
|
-
.get("/", (ctx:ContextType) => {
|
|
55
|
-
return ctx.text("Hello World!");
|
|
56
|
-
})
|
|
57
|
-
.any("/any",(ctx) => {
|
|
58
|
-
return ctx.json({msg:"any"})
|
|
59
|
-
})
|
|
60
|
-
.get("/post",(ctx) =>{
|
|
61
|
-
return ctx.json({msg:"get"})
|
|
62
|
-
})
|
|
63
|
-
.post("/post",(ctx) =>{
|
|
64
|
-
return ctx.json({msg:"post"})
|
|
65
|
-
})
|
|
66
|
-
.get("/test/:id/:name", (ctx:ContextType) => {
|
|
67
|
-
const id = ctx.getParams("id")
|
|
68
|
-
const name = ctx.getParams("name")
|
|
69
|
-
return ctx.text("How are you?"+id+name);
|
|
70
|
-
})
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
app.register("/api/user", userRoute)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
app.listen(port)
|