@increase21/simplenodejs 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ export { CreateSimpleJsHttpServer } from "./server";
2
+ export * from "./utils/helpers";
3
+ export { Middleware, ErrorMiddleware, SimpleJsServer } from "./typings/general";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.CreateSimpleJsHttpServer = void 0;
18
+ var server_1 = require("./server");
19
+ Object.defineProperty(exports, "CreateSimpleJsHttpServer", { enumerable: true, get: function () { return server_1.CreateSimpleJsHttpServer; } });
20
+ __exportStar(require("./utils/helpers"), exports);
21
+ // Optional: plugins
22
+ // export { SecurityPlugin } from "./plugins/SecurityPlugin";
@@ -0,0 +1,8 @@
1
+ import { RequestObject, ResponseObject } from "./typings/context";
2
+ export interface ControllerMeta {
3
+ name: string;
4
+ file: string;
5
+ Controller: any;
6
+ }
7
+ export declare function loadControllers(root?: string): Map<string, ControllerMeta>;
8
+ export declare function route(req: RequestObject, res: ResponseObject, controllersDir?: string): Promise<void>;
package/dist/router.js ADDED
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.loadControllers = loadControllers;
7
+ exports.route = route;
8
+ // router.ts
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ function loadControllers(root = "controllers") {
12
+ const base = node_path_1.default.resolve(process.cwd(), root);
13
+ const map = new Map();
14
+ //walk up
15
+ function walk(dir) {
16
+ //get all the file in the directory
17
+ for (const file of node_fs_1.default.readdirSync(dir)) {
18
+ //add the file name and path
19
+ const full = node_path_1.default.join(dir, file);
20
+ //load direct and reload the files
21
+ if (node_fs_1.default.statSync(full).isDirectory())
22
+ walk(full);
23
+ //if it's file load the file
24
+ else if (file.endsWith(".js") || file.endsWith(".ts")) {
25
+ const mod = require(full);
26
+ const Controller = mod.default;
27
+ if (Controller) {
28
+ const key = full.replace(base, "").replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
29
+ map.set(key.toLowerCase(), { name: Controller.name, file: full, Controller });
30
+ }
31
+ }
32
+ }
33
+ }
34
+ walk(base);
35
+ return map;
36
+ }
37
+ const controllers = loadControllers();
38
+ async function route(req, res, controllersDir) {
39
+ // console.log("Router is called")
40
+ const url = new URL(req.url, "http://localhost");
41
+ const parts = url.pathname.replace(/^\/+|\/+$/g, "").split("/");
42
+ const controllerPath = "/" + parts.slice(0, -1).join("/");
43
+ const methodName = parts[parts.length - 1] || "index";
44
+ const id = parts[parts.length];
45
+ const meta = controllers.get(controllerPath.toLowerCase());
46
+ if (!meta)
47
+ return res.status(404).text("The requested resource does not exist");
48
+ const ControllerClass = meta.Controller;
49
+ const controller = new ControllerClass(req, res);
50
+ if (typeof controller[methodName] !== "function") {
51
+ return res.status(404).text("The requested resource does not exist");
52
+ }
53
+ const result = await controller[methodName](id);
54
+ if (!res.writableEnded && result !== undefined) {
55
+ res.setHeader("Content-Type", "application/json");
56
+ res.end(JSON.stringify(result));
57
+ }
58
+ }
@@ -0,0 +1,4 @@
1
+ import { IncomingMessage, ServerResponse } from "http";
2
+ import { Middleware, RequestObject, ResponseObject, SimpleJsServer } from "./typings/general";
3
+ export declare function compose(middlewares: Middleware[]): (req: RequestObject, res: ResponseObject) => Promise<void>;
4
+ export declare const CreateSimpleJsHttpServer: (handler?: (req: IncomingMessage, res: ServerResponse) => void) => SimpleJsServer;
package/dist/server.js ADDED
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CreateSimpleJsHttpServer = void 0;
7
+ exports.compose = compose;
8
+ const http_1 = __importDefault(require("http"));
9
+ const router_1 = require("./router");
10
+ const extension = (req, res) => {
11
+ //for response status
12
+ res.status = (code) => {
13
+ if (!/^\d+/.test(String(code)) || typeof code !== "number")
14
+ throw new Error("Status code expected to be number but got " + typeof code);
15
+ res.statusCode = code ? code : 200;
16
+ return res;
17
+ };
18
+ ///convert the response to JSON
19
+ res.json = (param) => {
20
+ res.setHeader('Content-Type', 'application/json');
21
+ res.end(JSON.stringify(param));
22
+ };
23
+ //convert the response to text/plain
24
+ res.text = (param) => {
25
+ res.setHeader('Content-Type', 'text/plain');
26
+ res.end(param);
27
+ };
28
+ };
29
+ function compose(middlewares) {
30
+ return async function (req, res) {
31
+ let idx = -1;
32
+ async function dispatch(i) {
33
+ if (i <= idx)
34
+ throw new Error("next() called twice");
35
+ idx = i;
36
+ const fn = middlewares[i];
37
+ if (!fn)
38
+ return;
39
+ try {
40
+ await fn(req, res, () => dispatch(i + 1));
41
+ }
42
+ catch (err) {
43
+ if (!res.writableEnded) {
44
+ res.status(500).json({ error: "Middleware error" });
45
+ }
46
+ }
47
+ }
48
+ await dispatch(0);
49
+ };
50
+ }
51
+ const CreateSimpleJsHttpServer = (handler) => {
52
+ const middlewares = [];
53
+ const errorMiddlewares = [];
54
+ const plugins = [];
55
+ const server = http_1.default.createServer(async (req, res) => {
56
+ extension(req, res);
57
+ const run = compose(middlewares);
58
+ try {
59
+ handler && await handler(req, res);
60
+ if (res.writableEnded)
61
+ return;
62
+ await run(req, res);
63
+ //if the request has ended stop here
64
+ if (res.writableEnded)
65
+ return;
66
+ await (0, router_1.route)(req, res);
67
+ }
68
+ catch (err) {
69
+ res.statusCode = 500;
70
+ res.end("Internal Server Error");
71
+ }
72
+ });
73
+ server.setTimeout(60000); //60Seconds
74
+ server.use = mw => { middlewares.push(mw); };
75
+ server.useError = mw => errorMiddlewares.push(mw);
76
+ server.register = async (plugin, opts) => {
77
+ plugins.push(plugin);
78
+ await plugin(server, opts);
79
+ };
80
+ return server;
81
+ };
82
+ exports.CreateSimpleJsHttpServer = CreateSimpleJsHttpServer;
@@ -0,0 +1,18 @@
1
+ import { IncomingMessage, ServerResponse } from "http";
2
+ export interface Context {
3
+ req: IncomingMessage;
4
+ res: ServerResponse;
5
+ body?: any;
6
+ params?: Record<string, string>;
7
+ }
8
+ export interface RequestObject extends IncomingMessage {
9
+ body?: any;
10
+ query?: any;
11
+ _server_environment?: 'dev' | 'stag' | 'live';
12
+ _body_size?: 0;
13
+ }
14
+ export interface ResponseObject extends ServerResponse {
15
+ status: (value: number) => ResponseObject;
16
+ json: (value: object) => void;
17
+ text: (value?: string) => void;
18
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,22 @@
1
+ import http, { IncomingMessage, ServerResponse } from "http";
2
+ export type Next = () => Promise<void> | void;
3
+ export type Plugin = (app: SimpleJsServer, opts?: any) => Promise<void> | void;
4
+ export type Middleware = (req: RequestObject, res: ResponseObject, next: () => Promise<void> | void) => Promise<void> | void;
5
+ export type ErrorMiddleware = (err: any, req: RequestObject, res: ResponseObject, next: Next) => Promise<void> | void;
6
+ export interface SimpleJsServer extends http.Server {
7
+ use(mw: Middleware): Promise<any> | void;
8
+ useError: (mw: ErrorMiddleware) => void;
9
+ register: (plugin: Plugin, opts?: any) => Promise<void>;
10
+ }
11
+ export interface RequestObject extends IncomingMessage {
12
+ body?: any;
13
+ query?: any;
14
+ _server_environment?: 'dev' | 'stag' | 'live';
15
+ _body_size?: 0;
16
+ }
17
+ export interface ResponseObject extends ServerResponse {
18
+ status: (value: number) => ResponseObject;
19
+ json: (value: object) => void;
20
+ text: (value?: string) => void;
21
+ }
22
+ export type AcceptHeaderValue = 'application/media' | 'application/text';
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
1
+ import { RequestObject, ResponseObject } from "../typings/context";
2
+ import { ErrorMiddleware, Middleware, SimpleJsServer } from "../typings/general";
3
+ export declare function SetRequestCORS(opts: {
4
+ name: string;
5
+ value: string;
6
+ }[]): (req: RequestObject, res: ResponseObject, next: any) => Promise<void>;
7
+ export declare function SetRateLimiter(opts: {
8
+ windowMs: number;
9
+ max: number;
10
+ keyGenerator?: (req: any) => string;
11
+ }): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
12
+ export declare function SetBodyParser(opts: {
13
+ limit?: string | number;
14
+ json?: boolean;
15
+ }): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
16
+ export declare function composeWithError(middlewares: Middleware[], errorMiddlewares: ErrorMiddleware[]): (req: RequestObject, res: ResponseObject) => Promise<void>;
17
+ export declare function SecurityPlugin(app: SimpleJsServer, opts: any): void;
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SetRequestCORS = SetRequestCORS;
7
+ exports.SetRateLimiter = SetRateLimiter;
8
+ exports.SetBodyParser = SetBodyParser;
9
+ exports.composeWithError = composeWithError;
10
+ exports.SecurityPlugin = SecurityPlugin;
11
+ const node_querystring_1 = __importDefault(require("node:querystring"));
12
+ // core/cors.ts
13
+ function SetRequestCORS(opts) {
14
+ return async (req, res, next) => {
15
+ const defaults = {
16
+ "Access-Control-Allow-Origin": "*",
17
+ "Access-Control-Allow-Headers": "Authorization",
18
+ "Access-Control-Allow-Methods": "GET, POST"
19
+ };
20
+ let merged = { ...defaults };
21
+ for (const { name, value } of opts) {
22
+ merged[name] = value; // overrides defaults if same key
23
+ }
24
+ //allow credentials only when origin specified
25
+ if (merged["Access-Control-Allow-Credentials"] === "true") {
26
+ merged["Access-Control-Allow-Origin"] = req.headers.origin || "null";
27
+ }
28
+ for (const [key, value] of Object.entries(merged)) {
29
+ res.setHeader(key, value);
30
+ }
31
+ if (req.method === "OPTIONS") {
32
+ res.status(204).text();
33
+ return;
34
+ }
35
+ await next();
36
+ };
37
+ }
38
+ // core/rateLimit.ts
39
+ function SetRateLimiter(opts) {
40
+ const store = new Map();
41
+ return async (req, res, next) => {
42
+ const key = opts.keyGenerator?.(req) || req.socket.remoteAddress || "global";
43
+ const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
44
+ const now = Date.now();
45
+ const entry = store.get(key) || { count: 0, ts: now };
46
+ if (now - entry.ts > opts.windowMs) {
47
+ entry.count = 0;
48
+ entry.ts = now;
49
+ }
50
+ entry.count++;
51
+ store.set(key, entry);
52
+ if (entry.count > opts.max) {
53
+ res.status(429).json({ error: "Too Many Requests" });
54
+ return;
55
+ }
56
+ setInterval(() => {
57
+ const now = Date.now();
58
+ for (const [k, v] of store) {
59
+ if (now - v.ts > opts.windowMs * 2)
60
+ store.delete(k);
61
+ }
62
+ }, opts.windowMs);
63
+ await next();
64
+ };
65
+ }
66
+ // core/body.ts
67
+ function SetBodyLimit(limit = "1mb") {
68
+ if (typeof limit === "number")
69
+ return limit;
70
+ const match = /^(\d+)(kb|mb)?$/i.exec(limit);
71
+ if (!match)
72
+ return 1024 * 1024;
73
+ const n = parseInt(match[1], 10);
74
+ const unit = match[2]?.toLowerCase();
75
+ if (unit === "kb")
76
+ return n * 1024;
77
+ if (unit === "mb")
78
+ return n * 1024 * 1024;
79
+ return n;
80
+ }
81
+ function SetBodyParser(opts) {
82
+ const maxSize = SetBodyLimit(opts.limit);
83
+ return async (req, res, next) => {
84
+ return new Promise(resolve => {
85
+ let size = 0;
86
+ let body = "";
87
+ req.on("data", chunk => {
88
+ size += chunk.length;
89
+ if (maxSize && size > maxSize) {
90
+ if (!res.writableEnded) {
91
+ res.status(413).json({ error: "Payload too large" });
92
+ }
93
+ req.destroy();
94
+ req.socket.destroy();
95
+ return;
96
+ }
97
+ //add the body
98
+ body += chunk;
99
+ });
100
+ req.on("end", () => {
101
+ if (res.writableEnded)
102
+ return resolve();
103
+ try {
104
+ if (body && !["application/text", "application/media"].includes(req.headers.accept)) {
105
+ req.body = JSON.parse(body);
106
+ //parse query
107
+ if (req.query) {
108
+ req.query = JSON.parse(JSON.stringify(node_querystring_1.default.parse(req.query)));
109
+ }
110
+ }
111
+ else {
112
+ req.body = body;
113
+ }
114
+ resolve(next());
115
+ }
116
+ catch (e) {
117
+ res.status(400).json({ error: "Invalid request body" });
118
+ return resolve();
119
+ }
120
+ });
121
+ req.on("error", () => {
122
+ if (!res.writableEnded) {
123
+ res.status(400).json({ error: "Request stream error" });
124
+ }
125
+ resolve();
126
+ });
127
+ });
128
+ };
129
+ }
130
+ function composeWithError(middlewares, errorMiddlewares) {
131
+ return async function (req, res) {
132
+ let idx = -1;
133
+ async function dispatch(i) {
134
+ if (i <= idx)
135
+ throw new Error("next() called twice");
136
+ idx = i;
137
+ const fn = middlewares[i];
138
+ if (!fn)
139
+ return;
140
+ try {
141
+ await fn(req, res, () => dispatch(i + 1));
142
+ }
143
+ catch (err) {
144
+ await dispatchError(err, 0);
145
+ }
146
+ }
147
+ async function dispatchError(err, i) {
148
+ const fn = errorMiddlewares[i];
149
+ if (!fn) {
150
+ if (!res.writableEnded) {
151
+ res.status(500).json({ error: "Unhandled error", detail: String(err) });
152
+ }
153
+ return;
154
+ }
155
+ await fn(err, req, res, () => dispatchError(err, i + 1));
156
+ }
157
+ await dispatch(0);
158
+ };
159
+ }
160
+ function SecurityPlugin(app, opts) {
161
+ app.use(SetRequestCORS(opts.cors || []));
162
+ app.use(SetRateLimiter(opts.rateLimit || { windowMs: 1000, max: 100 }));
163
+ app.use(SetBodyParser(opts.body || { limit: "1mb" }));
164
+ }
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@increase21/simplenodejs",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight Node.js HTTP framework with middleware and plugins",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist/**/*"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "node dist/test.js"
13
+ },
14
+ "keywords": ["http", "framework", "node", "typescript"],
15
+ "author": "Increase Nkanta",
16
+ "license": "MIT",
17
+ "devDependencies": {
18
+ "typescript": "^5.3.0"
19
+ }
20
+ }