@syntay/fastay 0.2.3 → 0.2.5
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/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -33
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +3 -0
- package/dist/types/request.d.ts +389 -0
- package/dist/types/request.d.ts.map +1 -0
- package/dist/types/request.js +1 -0
- package/package.json +4 -1
- package/fastay.png +0 -0
- package/src/app.ts +0 -328
- package/src/banner.ts +0 -11
- package/src/error-handler.ts +0 -48
- package/src/index.ts +0 -5
- package/src/logger.ts +0 -78
- package/src/middleware.ts +0 -107
- package/src/router.ts +0 -230
- package/src/types/express.d.ts +0 -8
- package/src/types/index.ts +0 -73
- package/src/utils/cookies.ts +0 -34
- package/src/utils/formDataMiddleware.ts +0 -155
- package/src/utils/wrapMiddleware.ts +0 -95
- package/tsconfig.build.json +0 -14
- package/tsconfig.json +0 -22
package/src/router.ts
DELETED
|
@@ -1,230 +0,0 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import { pathToFileURL } from 'url';
|
|
4
|
-
import { Application, Request, Response, NextFunction } from 'express';
|
|
5
|
-
import { logger } from './logger.js';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Converte caminho do arquivo em rota Express (somente arquivos route.ts)
|
|
9
|
-
*/
|
|
10
|
-
export function filePathToRoute(
|
|
11
|
-
apiDir: string,
|
|
12
|
-
filePath: string,
|
|
13
|
-
baseRoute: string
|
|
14
|
-
) {
|
|
15
|
-
const rel = path.relative(apiDir, filePath);
|
|
16
|
-
const parts = rel.split(path.sep);
|
|
17
|
-
const filename = parts.pop()!;
|
|
18
|
-
if (filename !== 'route.ts' && filename !== 'route.js') return null;
|
|
19
|
-
|
|
20
|
-
const segments = parts
|
|
21
|
-
.map((s) =>
|
|
22
|
-
s.startsWith('[') && s.endsWith(']') ? `:${s.slice(1, -1)}` : s
|
|
23
|
-
)
|
|
24
|
-
.filter(Boolean);
|
|
25
|
-
|
|
26
|
-
return `${baseRoute}/${segments.join('/')}`.replace(/\/+/g, '/');
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Retorna todos arquivos .ts/.js recursivamente
|
|
31
|
-
*/
|
|
32
|
-
export function collectFiles(dir: string): string[] {
|
|
33
|
-
let out: string[] = [];
|
|
34
|
-
const items = fs.readdirSync(dir, { withFileTypes: true });
|
|
35
|
-
for (const it of items) {
|
|
36
|
-
const full = path.join(dir, it.name);
|
|
37
|
-
if (it.isDirectory()) out = out.concat(collectFiles(full));
|
|
38
|
-
else if (/\.(ts|js|mts|mjs)$/.test(it.name)) out.push(full);
|
|
39
|
-
}
|
|
40
|
-
return out;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Wrapper para suportar return JSON/string/number e capturar erros runtime
|
|
45
|
-
*/
|
|
46
|
-
function wrapHandler(fn: Function, routePath: string, filePath: string) {
|
|
47
|
-
return async (req: Request, res: Response, next: NextFunction) => {
|
|
48
|
-
try {
|
|
49
|
-
const result = fn.length >= 2 ? await fn(req, res) : await fn(req);
|
|
50
|
-
|
|
51
|
-
if (res.headersSent) return;
|
|
52
|
-
if (result === undefined) return;
|
|
53
|
-
|
|
54
|
-
// Suporte a status e cookies customizado
|
|
55
|
-
// if (
|
|
56
|
-
// typeof result === 'object' &&
|
|
57
|
-
// 'status' in result &&
|
|
58
|
-
// 'body' in result &&
|
|
59
|
-
// typeof result.status === 'number'
|
|
60
|
-
// ) {
|
|
61
|
-
// return res.status(result.status).json(result.body);
|
|
62
|
-
// }
|
|
63
|
-
if (typeof result === 'object' && result !== null) {
|
|
64
|
-
const typedResult = result as {
|
|
65
|
-
status?: number;
|
|
66
|
-
body?: any;
|
|
67
|
-
cookies?: Record<string, { value: string; options?: any }>;
|
|
68
|
-
headers?: Record<string, string>;
|
|
69
|
-
redirect?: string;
|
|
70
|
-
file?: {
|
|
71
|
-
path: string;
|
|
72
|
-
filename?: string;
|
|
73
|
-
options?: any;
|
|
74
|
-
};
|
|
75
|
-
stream?: NodeJS.ReadableStream;
|
|
76
|
-
raw?: Buffer | string;
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
// redirect
|
|
80
|
-
if (typedResult.redirect) {
|
|
81
|
-
return res.redirect(typedResult.status ?? 302, typedResult.redirect);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
//headers
|
|
85
|
-
if (typedResult.headers) {
|
|
86
|
-
for (const [h, v] of Object.entries(typedResult.headers)) {
|
|
87
|
-
res.setHeader(h, v);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
//file
|
|
92
|
-
if (typedResult.file) {
|
|
93
|
-
const { path, filename, options } = typedResult.file;
|
|
94
|
-
|
|
95
|
-
if (filename) {
|
|
96
|
-
return res.download(path, filename, options);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
return res.download(path, options);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// stream
|
|
103
|
-
if (typedResult.stream) {
|
|
104
|
-
if (typedResult.headers) {
|
|
105
|
-
for (const [h, v] of Object.entries(typedResult.headers))
|
|
106
|
-
res.setHeader(h, v);
|
|
107
|
-
}
|
|
108
|
-
return typedResult.stream.pipe(res);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// raw
|
|
112
|
-
if (typedResult.raw) {
|
|
113
|
-
if (typedResult.headers) {
|
|
114
|
-
for (const [h, v] of Object.entries(typedResult.headers))
|
|
115
|
-
res.setHeader(h, v);
|
|
116
|
-
}
|
|
117
|
-
return res.status(typedResult.status ?? 200).send(typedResult.raw);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
if (typedResult.cookies) {
|
|
121
|
-
for (const [name, data] of Object.entries(typedResult.cookies)) {
|
|
122
|
-
res.cookie(name, data.value, data.options || {});
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const statusCode =
|
|
127
|
-
typeof result.status === 'number' ? result.status : 200;
|
|
128
|
-
|
|
129
|
-
const body = result.body ?? result; // se não existir body, retorna o objeto inteiro
|
|
130
|
-
return res.status(statusCode).json(body);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Suporte a retorno simples
|
|
134
|
-
if (typeof result === 'string') return res.send(result);
|
|
135
|
-
if (typeof result === 'number') return res.send(String(result));
|
|
136
|
-
return res.json(result);
|
|
137
|
-
} catch (err: any) {
|
|
138
|
-
const stack = err?.stack?.split('\n').slice(0, 3).join('\n') || '';
|
|
139
|
-
logger.error(`${err.name}: ${err.message}`);
|
|
140
|
-
next(err);
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Carrega todas as rotas do diretório apiDir
|
|
147
|
-
*/
|
|
148
|
-
export async function loadApiRoutes(
|
|
149
|
-
app: Application,
|
|
150
|
-
baseRoute: string,
|
|
151
|
-
apiDirectory: string
|
|
152
|
-
) {
|
|
153
|
-
const isDev = process.env.NODE_ENV !== 'production';
|
|
154
|
-
|
|
155
|
-
const apiDir = path.join(process.cwd(), isDev ? apiDirectory : 'dist/api');
|
|
156
|
-
|
|
157
|
-
if (!fs.existsSync(apiDir)) return 0;
|
|
158
|
-
|
|
159
|
-
const files = collectFiles(apiDir);
|
|
160
|
-
let cont = 0;
|
|
161
|
-
|
|
162
|
-
logger.group('Routes Loaded');
|
|
163
|
-
|
|
164
|
-
for (const file of files) {
|
|
165
|
-
const route = filePathToRoute(apiDir, file, baseRoute);
|
|
166
|
-
if (!route) continue;
|
|
167
|
-
|
|
168
|
-
try {
|
|
169
|
-
const fileUrl = pathToFileURL(file).href;
|
|
170
|
-
const mod = await import(fileUrl);
|
|
171
|
-
|
|
172
|
-
const httpMethods = [
|
|
173
|
-
'GET',
|
|
174
|
-
'POST',
|
|
175
|
-
'PUT',
|
|
176
|
-
'DELETE',
|
|
177
|
-
'PATCH',
|
|
178
|
-
'OPTIONS',
|
|
179
|
-
'HEAD',
|
|
180
|
-
];
|
|
181
|
-
|
|
182
|
-
for (const m of httpMethods) {
|
|
183
|
-
if (typeof mod[m] === 'function') {
|
|
184
|
-
(app as any)[m.toLowerCase()](
|
|
185
|
-
route,
|
|
186
|
-
wrapHandler(mod[m], route, file)
|
|
187
|
-
);
|
|
188
|
-
cont++;
|
|
189
|
-
logger.success(`Route: [${m}] ${route}`);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
if (mod.default && typeof mod.default === 'function') {
|
|
194
|
-
app.get(route, wrapHandler(mod.default, route, file));
|
|
195
|
-
cont++;
|
|
196
|
-
logger.success(`Route: [GET] ${route}`);
|
|
197
|
-
}
|
|
198
|
-
} catch (err: any) {
|
|
199
|
-
const stack = err?.stack?.split('\n').slice(0, 3).join('\n') || '';
|
|
200
|
-
// logger.error(
|
|
201
|
-
// `✗ Boot Error importing ${file}\n` +
|
|
202
|
-
// ` Message: ${err.message || 'Unknown error'}\n` +
|
|
203
|
-
// ` Stack: ${stack}`
|
|
204
|
-
// );
|
|
205
|
-
|
|
206
|
-
let fileInfo = '';
|
|
207
|
-
if (err.stack) {
|
|
208
|
-
const stackLine = err.stack.split('\n')[1]; // pega primeira linha depois do erro
|
|
209
|
-
const match = stackLine.match(/\((.*):(\d+):(\d+)\)/);
|
|
210
|
-
if (match) {
|
|
211
|
-
const [_, file, line, col] = match;
|
|
212
|
-
fileInfo = `${file}:${line}:${col}`;
|
|
213
|
-
|
|
214
|
-
// Tenta mostrar o trecho da linha que deu erro
|
|
215
|
-
if (fs.existsSync(file)) {
|
|
216
|
-
const codeLines = fs.readFileSync(file, 'utf-8').split('\n');
|
|
217
|
-
const codeSnippet = codeLines[parseInt(line) - 1].trim();
|
|
218
|
-
fileInfo += ` → ${codeSnippet}`;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// logger.group(`✗ Boot Error importing ${file}`);
|
|
224
|
-
logger.error(`${err.name}: ${err.message}`);
|
|
225
|
-
if (fileInfo) logger.error(`Location: ${fileInfo}`);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
return cont;
|
|
230
|
-
}
|
package/src/types/express.d.ts
DELETED
package/src/types/index.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import './express';
|
|
2
|
-
import {
|
|
3
|
-
Request as ExpressRequest,
|
|
4
|
-
Response as ExpressResponse,
|
|
5
|
-
NextFunction,
|
|
6
|
-
} from 'express';
|
|
7
|
-
|
|
8
|
-
export interface CookieItem {
|
|
9
|
-
value: string;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export interface RequestCookies {
|
|
13
|
-
/**
|
|
14
|
-
* Retrieves a cookie by its name.
|
|
15
|
-
* @param name - The name of the cookie to retrieve.
|
|
16
|
-
* @returns An object containing the cookie's value, or undefined if not found.
|
|
17
|
-
*/
|
|
18
|
-
get(name: string): CookieItem | undefined;
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Checks if a cookie with the given name exists.
|
|
22
|
-
* @param name - The name of the cookie to check.
|
|
23
|
-
* @returns True if the cookie exists, false otherwise.
|
|
24
|
-
*/
|
|
25
|
-
has(name: string): boolean;
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Returns all cookies as a key-value object.
|
|
29
|
-
* @returns An object where keys are cookie names and values are cookie values.
|
|
30
|
-
*/
|
|
31
|
-
all(): Record<string, string>;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export interface Request extends ExpressRequest {
|
|
35
|
-
/**
|
|
36
|
-
* Represents the cookies sent in a request.
|
|
37
|
-
*/
|
|
38
|
-
cookies: RequestCookies;
|
|
39
|
-
formData: () => Promise<FormData>;
|
|
40
|
-
// params:
|
|
41
|
-
// query:
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export type Response = ExpressResponse;
|
|
45
|
-
export type Next = NextFunction;
|
|
46
|
-
|
|
47
|
-
declare global {
|
|
48
|
-
type FastayResponse = {
|
|
49
|
-
status?: number;
|
|
50
|
-
body?: any;
|
|
51
|
-
cookies?: Record<string, { value: string; options?: any }>;
|
|
52
|
-
headers?: Record<string, string>;
|
|
53
|
-
redirect?: string;
|
|
54
|
-
file?: { path: string; filename?: string; options?: any };
|
|
55
|
-
stream?: NodeJS.ReadableStream;
|
|
56
|
-
raw?: Buffer | string;
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export type RouteHandler =
|
|
61
|
-
| (() => FastayResponse | any)
|
|
62
|
-
| ((req: Request) => FastayResponse | any)
|
|
63
|
-
| ((req: Request, res: Response) => FastayResponse | any);
|
|
64
|
-
|
|
65
|
-
export interface CookieItem {
|
|
66
|
-
value: string;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// declare module 'express-serve-static-core' {
|
|
70
|
-
// interface Request {
|
|
71
|
-
// typedCookies: RequestCookies | any;
|
|
72
|
-
// }
|
|
73
|
-
// }
|
package/src/utils/cookies.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
// utils/cookies.ts
|
|
2
|
-
import { IncomingMessage } from 'http';
|
|
3
|
-
|
|
4
|
-
export class RequestCookies {
|
|
5
|
-
private cookies: Map<string, string> = new Map();
|
|
6
|
-
|
|
7
|
-
constructor(cookieHeader: string | undefined) {
|
|
8
|
-
if (!cookieHeader) return;
|
|
9
|
-
|
|
10
|
-
cookieHeader.split(';').forEach((cookie) => {
|
|
11
|
-
const [name, ...rest] = cookie.trim().split('=');
|
|
12
|
-
if (!name) return;
|
|
13
|
-
this.cookies.set(name, decodeURIComponent(rest.join('=')));
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
public get(name: string) {
|
|
18
|
-
const value = this.cookies.get(name);
|
|
19
|
-
if (!value) return undefined;
|
|
20
|
-
return { value };
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
public has(name: string) {
|
|
24
|
-
return this.cookies.has(name);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
public all() {
|
|
28
|
-
const obj: Record<string, string> = {};
|
|
29
|
-
this.cookies.forEach((v, k) => (obj[k] = v));
|
|
30
|
-
return obj;
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export const cookies = RequestCookies;
|
|
@@ -1,155 +0,0 @@
|
|
|
1
|
-
import Busboy from 'busboy';
|
|
2
|
-
|
|
3
|
-
type FieldMap = Record<string, string | string[]>;
|
|
4
|
-
type FileInfo = {
|
|
5
|
-
filename: string;
|
|
6
|
-
encoding: string;
|
|
7
|
-
mimeType: string;
|
|
8
|
-
size: number;
|
|
9
|
-
buffer: Buffer;
|
|
10
|
-
};
|
|
11
|
-
type FileMap = Record<string, File[]>;
|
|
12
|
-
|
|
13
|
-
// Classe File compatível com a do browser
|
|
14
|
-
export class File {
|
|
15
|
-
name: string;
|
|
16
|
-
type: string;
|
|
17
|
-
size: number;
|
|
18
|
-
buffer: Buffer;
|
|
19
|
-
|
|
20
|
-
constructor(file: FileInfo) {
|
|
21
|
-
this.name = file.filename;
|
|
22
|
-
this.type = file.mimeType;
|
|
23
|
-
this.size = file.size;
|
|
24
|
-
this.buffer = file.buffer;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
arrayBuffer() {
|
|
28
|
-
return this.buffer.buffer.slice(
|
|
29
|
-
this.buffer.byteOffset,
|
|
30
|
-
this.buffer.byteOffset + this.buffer.byteLength
|
|
31
|
-
);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function formDataMiddleware() {
|
|
36
|
-
return function (req: any, res: any, next: any) {
|
|
37
|
-
if (typeof req.formData === 'function') return next();
|
|
38
|
-
|
|
39
|
-
req.formData = () =>
|
|
40
|
-
new Promise((resolve, reject) => {
|
|
41
|
-
const bb = Busboy({ headers: req.headers });
|
|
42
|
-
|
|
43
|
-
const fields: FieldMap = {};
|
|
44
|
-
const files: FileMap = {};
|
|
45
|
-
|
|
46
|
-
bb.on('field', (name, value) => {
|
|
47
|
-
if (name.endsWith('[]')) {
|
|
48
|
-
const key = name.slice(0, -2);
|
|
49
|
-
if (!fields[key]) fields[key] = [];
|
|
50
|
-
(fields[key] as string[]).push(value);
|
|
51
|
-
} else {
|
|
52
|
-
fields[name] = value;
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
bb.on('file', (name, file, info) => {
|
|
57
|
-
const chunks: Buffer[] = [];
|
|
58
|
-
|
|
59
|
-
file.on('data', (chunk) => chunks.push(chunk));
|
|
60
|
-
|
|
61
|
-
file.on('end', () => {
|
|
62
|
-
const buffer = Buffer.concat(chunks);
|
|
63
|
-
|
|
64
|
-
const fileObj = new File({
|
|
65
|
-
filename: info.filename,
|
|
66
|
-
encoding: info.encoding,
|
|
67
|
-
mimeType: info.mimeType,
|
|
68
|
-
size: buffer.length,
|
|
69
|
-
buffer,
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
if (!files[name]) files[name] = [];
|
|
73
|
-
files[name].push(fileObj);
|
|
74
|
-
});
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
bb.on('finish', () => {
|
|
78
|
-
resolve(createFormDataLike(fields, files));
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
bb.on('error', reject);
|
|
82
|
-
|
|
83
|
-
req.pipe(bb);
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
next();
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function createFormDataLike(fields: FieldMap, files: FileMap) {
|
|
91
|
-
return {
|
|
92
|
-
get(key: string) {
|
|
93
|
-
if (files[key]) return files[key][0];
|
|
94
|
-
return fields[key] ?? null;
|
|
95
|
-
},
|
|
96
|
-
|
|
97
|
-
getAll(key: string) {
|
|
98
|
-
if (files[key]) return files[key];
|
|
99
|
-
const val = fields[key];
|
|
100
|
-
return Array.isArray(val) ? val : val ? [val] : [];
|
|
101
|
-
},
|
|
102
|
-
|
|
103
|
-
has(key: string) {
|
|
104
|
-
return !!fields[key] || !!files[key];
|
|
105
|
-
},
|
|
106
|
-
|
|
107
|
-
append(key: string, value: any) {
|
|
108
|
-
if (value instanceof File) {
|
|
109
|
-
if (!files[key]) files[key] = [];
|
|
110
|
-
files[key].push(value);
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
if (!fields[key]) {
|
|
115
|
-
fields[key] = value;
|
|
116
|
-
} else if (Array.isArray(fields[key])) {
|
|
117
|
-
(fields[key] as string[]).push(value);
|
|
118
|
-
} else {
|
|
119
|
-
fields[key] = [fields[key] as string, value];
|
|
120
|
-
}
|
|
121
|
-
},
|
|
122
|
-
|
|
123
|
-
set(key: string, value: any) {
|
|
124
|
-
if (value instanceof File) {
|
|
125
|
-
files[key] = [value];
|
|
126
|
-
delete fields[key];
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
fields[key] = value;
|
|
131
|
-
delete files[key];
|
|
132
|
-
},
|
|
133
|
-
|
|
134
|
-
delete(key: string) {
|
|
135
|
-
delete fields[key];
|
|
136
|
-
delete files[key];
|
|
137
|
-
},
|
|
138
|
-
|
|
139
|
-
*entries() {
|
|
140
|
-
for (const [k, v] of Object.entries(fields)) {
|
|
141
|
-
if (Array.isArray(v)) {
|
|
142
|
-
for (const item of v) yield [k, item];
|
|
143
|
-
} else {
|
|
144
|
-
yield [k, v];
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
for (const [k, arr] of Object.entries(files)) {
|
|
149
|
-
for (const file of arr) yield [k, file];
|
|
150
|
-
}
|
|
151
|
-
},
|
|
152
|
-
|
|
153
|
-
raw: { fields, files },
|
|
154
|
-
};
|
|
155
|
-
}
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { Request, Response, NextFunction } from 'express';
|
|
2
|
-
import { logger } from '../logger.js';
|
|
3
|
-
|
|
4
|
-
export type MiddlewareFn = (
|
|
5
|
-
req: Request,
|
|
6
|
-
res: Response,
|
|
7
|
-
next: NextFunction
|
|
8
|
-
) => any;
|
|
9
|
-
|
|
10
|
-
const color = {
|
|
11
|
-
cyan: (s: string) => `\x1b[36m${s}\x1b[0m`,
|
|
12
|
-
gray: (s: string) => `\x1b[90m${s}\x1b[0m`,
|
|
13
|
-
red: (s: string) => `\x1b[31m${s}\x1b[0m`,
|
|
14
|
-
yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
|
|
15
|
-
green: (s: string) => `\x1b[32m${s}\x1b[0m`,
|
|
16
|
-
white: (s: string) => `\x1b[37m${s}\x1b[0m`,
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Formata uma função para exibição bonitinha
|
|
21
|
-
*/
|
|
22
|
-
function formatFunction(fn: Function): string {
|
|
23
|
-
let code = fn.toString();
|
|
24
|
-
|
|
25
|
-
// deixa com quebras de linha
|
|
26
|
-
code = code.replace(/;/g, ';\n');
|
|
27
|
-
|
|
28
|
-
// tenta dar indentação
|
|
29
|
-
code = code
|
|
30
|
-
.replace(/{/g, '{\n ')
|
|
31
|
-
.replace(/}/g, '\n}')
|
|
32
|
-
.replace(/\n\s*\n/g, '\n');
|
|
33
|
-
|
|
34
|
-
return code.trim();
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Verifica se next() ou return existem
|
|
39
|
-
*/
|
|
40
|
-
function validateMiddlewareCode(mw: MiddlewareFn) {
|
|
41
|
-
const raw = mw.toString();
|
|
42
|
-
const name = mw.name || 'anonymous';
|
|
43
|
-
|
|
44
|
-
const cleaned = raw
|
|
45
|
-
.replace(/\/\/.*$/gm, '')
|
|
46
|
-
.replace(/\/\*[\s\S]*?\*\//gm, '');
|
|
47
|
-
|
|
48
|
-
const hasNext = /next\s*\(/.test(cleaned);
|
|
49
|
-
const hasReturn = /\breturn\b/.test(cleaned);
|
|
50
|
-
|
|
51
|
-
if (!hasNext && !hasReturn) {
|
|
52
|
-
const prettyCode = formatFunction(mw);
|
|
53
|
-
|
|
54
|
-
const message = [
|
|
55
|
-
`${color.red('⨯ Fastay Middleware Error')}`,
|
|
56
|
-
``,
|
|
57
|
-
`The middleware ${color.yellow(
|
|
58
|
-
`"${name}"`
|
|
59
|
-
)} does not call next() or return any value.`,
|
|
60
|
-
`This will halt the middleware chain and block the request pipeline.`,
|
|
61
|
-
``,
|
|
62
|
-
`▌ Middleware Source`,
|
|
63
|
-
color.gray(prettyCode),
|
|
64
|
-
``,
|
|
65
|
-
`${color.cyan('▌ How to fix')}`,
|
|
66
|
-
`Ensure your middleware ends with either:`,
|
|
67
|
-
` • ${color.green('next()')}`,
|
|
68
|
-
` • ${color.green('return ...')}`,
|
|
69
|
-
``,
|
|
70
|
-
`Fastay cannot continue until this middleware is fixed.`,
|
|
71
|
-
].join('\n');
|
|
72
|
-
|
|
73
|
-
const err = new Error(message);
|
|
74
|
-
err.name = 'FastayMiddlewareError';
|
|
75
|
-
throw err;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Wrapper final
|
|
81
|
-
*/
|
|
82
|
-
export function wrapMiddleware(mw: MiddlewareFn): MiddlewareFn {
|
|
83
|
-
const name = mw.name || 'anonymous';
|
|
84
|
-
validateMiddlewareCode(mw);
|
|
85
|
-
|
|
86
|
-
// retorna middleware "puro"
|
|
87
|
-
return async (req: Request, res: Response, next: NextFunction) => {
|
|
88
|
-
try {
|
|
89
|
-
await mw(req, res, next);
|
|
90
|
-
} catch (err) {
|
|
91
|
-
logger.error(`[${name}] middleware error: ${err}`);
|
|
92
|
-
next(err);
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
}
|
package/tsconfig.build.json
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "./tsconfig.json",
|
|
3
|
-
"compilerOptions": {
|
|
4
|
-
"outDir": "dist",
|
|
5
|
-
"declaration": true,
|
|
6
|
-
"sourceMap": false,
|
|
7
|
-
"rootDir": "src",
|
|
8
|
-
"module": "ES2022",
|
|
9
|
-
"target": "ES2020",
|
|
10
|
-
"emitDeclarationOnly": false,
|
|
11
|
-
"resolveJsonModule": true
|
|
12
|
-
},
|
|
13
|
-
"include": ["src", "src/types/**/*.d.ts"]
|
|
14
|
-
}
|
package/tsconfig.json
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ES2020",
|
|
4
|
-
"module": "CommonJS",
|
|
5
|
-
"rootDir": "src",
|
|
6
|
-
"outDir": "dist",
|
|
7
|
-
"baseUrl": ".",
|
|
8
|
-
"strict": true,
|
|
9
|
-
"declaration": true,
|
|
10
|
-
"emitDeclarationOnly": false,
|
|
11
|
-
"declarationMap": true,
|
|
12
|
-
"esModuleInterop": true,
|
|
13
|
-
"forceConsistentCasingInFileNames": true,
|
|
14
|
-
"skipLibCheck": true,
|
|
15
|
-
"moduleResolution": "node",
|
|
16
|
-
"resolveJsonModule": true,
|
|
17
|
-
"allowSyntheticDefaultImports": true,
|
|
18
|
-
"typeRoots": ["./node_modules/@types", "./src/types"]
|
|
19
|
-
},
|
|
20
|
-
"include": ["src", "src/types"],
|
|
21
|
-
"exclude": ["node_modules", "dist"]
|
|
22
|
-
}
|