viojs-middlewares 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,16 @@
1
+ import { BaseContext, Next } from 'viojs-core';
2
+ export interface CookieOptions {
3
+ maxAge?: number;
4
+ path?: string;
5
+ domain?: string;
6
+ secure?: boolean;
7
+ httpOnly?: boolean;
8
+ sameSite?: 'Strict' | 'Lax' | 'None';
9
+ }
10
+ declare module 'viojs-core' {
11
+ interface BaseContext {
12
+ getCookie(name: string): string | undefined;
13
+ setCookie(name: string, value: string, options?: CookieOptions): void;
14
+ }
15
+ }
16
+ export declare const cookieMiddleware: () => (ctx: BaseContext, next: Next) => Promise<void>;
package/dist/cookie.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cookieMiddleware = void 0;
4
+ const cookieMiddleware = () => {
5
+ return async (ctx, next) => {
6
+ let parsedCookies;
7
+ ctx.getCookie = (name) => {
8
+ if (!parsedCookies) {
9
+ parsedCookies = {};
10
+ const cookieHeader = ctx.headers['cookie'];
11
+ if (cookieHeader) {
12
+ cookieHeader.split(';').forEach(c => {
13
+ const [k, v] = c.split('=');
14
+ if (k && v) {
15
+ parsedCookies[k.trim()] = decodeURIComponent(v.trim());
16
+ }
17
+ });
18
+ }
19
+ }
20
+ return parsedCookies[name];
21
+ };
22
+ ctx.setCookie = (name, value, options = {}) => {
23
+ let cookieStr = `${name}=${encodeURIComponent(value)}`;
24
+ if (options.maxAge !== undefined)
25
+ cookieStr += `; Max-Age=${options.maxAge}`;
26
+ if (options.path)
27
+ cookieStr += `; Path=${options.path}`;
28
+ if (options.domain)
29
+ cookieStr += `; Domain=${options.domain}`;
30
+ if (options.secure)
31
+ cookieStr += `; Secure`;
32
+ if (options.httpOnly)
33
+ cookieStr += `; HttpOnly`;
34
+ if (options.sameSite)
35
+ cookieStr += `; SameSite=${options.sameSite}`;
36
+ if (!ctx.responseHeaders['Set-Cookie']) {
37
+ ctx.responseHeaders['Set-Cookie'] = [];
38
+ }
39
+ else if (typeof ctx.responseHeaders['Set-Cookie'] === 'string') {
40
+ ctx.responseHeaders['Set-Cookie'] = [ctx.responseHeaders['Set-Cookie']];
41
+ }
42
+ ctx.responseHeaders['Set-Cookie'].push(cookieStr);
43
+ };
44
+ await next();
45
+ };
46
+ };
47
+ exports.cookieMiddleware = cookieMiddleware;
@@ -0,0 +1,2 @@
1
+ export { cookieMiddleware as cookie } from './cookie';
2
+ export { staticMiddleware as staticFiles } from './static';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.staticFiles = exports.cookie = void 0;
4
+ var cookie_1 = require("./cookie");
5
+ Object.defineProperty(exports, "cookie", { enumerable: true, get: function () { return cookie_1.cookieMiddleware; } });
6
+ var static_1 = require("./static");
7
+ Object.defineProperty(exports, "staticFiles", { enumerable: true, get: function () { return static_1.staticMiddleware; } });
@@ -0,0 +1,6 @@
1
+ import { Middleware } from 'viojs-core';
2
+ export interface StaticOptions {
3
+ index?: string;
4
+ maxAge?: number;
5
+ }
6
+ export declare const staticMiddleware: (rootPath: string, options?: StaticOptions) => Middleware;
package/dist/static.js ADDED
@@ -0,0 +1,76 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.staticMiddleware = void 0;
37
+ const path = __importStar(require("path"));
38
+ const staticMiddleware = (rootPath, options = {}) => {
39
+ return async (ctx, next) => {
40
+ // Only serve static files on GET or HEAD
41
+ if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
42
+ return await next();
43
+ }
44
+ // Extremely simple static mapping
45
+ let reqPath = decodeURIComponent(ctx.url);
46
+ // Handle index file fallback for root
47
+ if (reqPath === '/' && options.index) {
48
+ reqPath = '/' + options.index;
49
+ }
50
+ // Prevent directory traversal attacks
51
+ const normalizedPath = path.normalize(reqPath).replace(/^(\.\.(\/|\\|$))+/, '');
52
+ const targetPath = path.join(rootPath, normalizedPath);
53
+ // Security check: ensure target path is still inside root path
54
+ if (!targetPath.startsWith(rootPath)) {
55
+ return await next();
56
+ }
57
+ try {
58
+ const stat = require('fs').statSync(targetPath);
59
+ if (stat.isFile()) {
60
+ // Expose a Cache-Control if user provided maxAge
61
+ if (options.maxAge !== undefined) {
62
+ ctx.responseHeaders['Cache-Control'] = `public, max-age=${options.maxAge}`;
63
+ }
64
+ // Stream the file seamlessly
65
+ ctx.sendFile(targetPath);
66
+ // Do NOT call next(), as static file served effectively handles the request
67
+ return;
68
+ }
69
+ }
70
+ catch (e) {
71
+ // File not found or inaccessible, just pass to the next middleware (e.g. router)
72
+ }
73
+ await next();
74
+ };
75
+ };
76
+ exports.staticMiddleware = staticMiddleware;
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "viojs-middlewares",
3
+ "version": "1.0.0",
4
+ "description": "Official middlewares for @vio/core framework",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "package.json"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsc"
13
+ },
14
+ "dependencies": {},
15
+ "devDependencies": {
16
+ "typescript": "^5.3.3"
17
+ },
18
+ "peerDependencies": {
19
+ "viojs-core": "*"
20
+ }
21
+ }