@syntay/fastay 0.2.4 → 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/types/request.d.ts +6 -1
- package/dist/types/request.d.ts.map +1 -1
- 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 -6
- 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/types/request.ts +0 -457
- 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
|
-
// }
|