azurajs 3.0.0 → 3.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.
Files changed (106) hide show
  1. package/dist/config/index.js +128 -6
  2. package/dist/config/index.js.map +1 -1
  3. package/dist/config/index.mjs +130 -1
  4. package/dist/config/index.mjs.map +1 -1
  5. package/dist/core/index.js +1100 -11
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +1102 -3
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/decorators/index.js +117 -87
  10. package/dist/decorators/index.js.map +1 -1
  11. package/dist/decorators/index.mjs +98 -1
  12. package/dist/decorators/index.mjs.map +1 -1
  13. package/dist/index.js +2592 -236
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +2537 -9
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/middleware/index.js +16 -7
  18. package/dist/middleware/index.js.map +1 -1
  19. package/dist/middleware/index.mjs +17 -1
  20. package/dist/middleware/index.mjs.map +1 -1
  21. package/dist/plugins/index.js +1056 -73
  22. package/dist/plugins/index.js.map +1 -1
  23. package/dist/plugins/index.mjs +1042 -1
  24. package/dist/plugins/index.mjs.map +1 -1
  25. package/dist/types/index.js +49 -12
  26. package/dist/types/index.js.map +1 -1
  27. package/dist/types/index.mjs +49 -2
  28. package/dist/types/index.mjs.map +1 -1
  29. package/dist/utils/index.js +551 -50
  30. package/dist/utils/index.js.map +1 -1
  31. package/dist/utils/index.mjs +541 -3
  32. package/dist/utils/index.mjs.map +1 -1
  33. package/package.json +52 -18
  34. package/{dist/chunk-DR254CWJ.mjs → src/config/ConfigModule.ts} +169 -132
  35. package/src/config/index.ts +1 -0
  36. package/src/core/index.ts +2 -0
  37. package/src/core/router.ts +284 -0
  38. package/{dist/chunk-EYAHUNC7.mjs → src/core/server.ts} +590 -699
  39. package/src/decorators/Route.ts +110 -0
  40. package/src/decorators/index.ts +23 -0
  41. package/src/index.ts +12 -0
  42. package/src/middleware/LoggingMiddleware.ts +20 -0
  43. package/src/middleware/index.ts +1 -0
  44. package/src/plugins/CORSPlugin.ts +56 -0
  45. package/src/plugins/CircuitBreakerPlugin.ts +84 -0
  46. package/src/plugins/CompressionPlugin.ts +80 -0
  47. package/src/plugins/ETagPlugin.ts +31 -0
  48. package/src/plugins/HealthCheckPlugin.ts +57 -0
  49. package/src/plugins/HelmetPlugin.ts +89 -0
  50. package/src/plugins/JWTPlugin.ts +132 -0
  51. package/src/plugins/MultipartPlugin.ts +168 -0
  52. package/src/plugins/ProxyPlugin.ts +89 -0
  53. package/src/plugins/RateLimitPlugin.ts +96 -0
  54. package/src/plugins/RequestIdPlugin.ts +21 -0
  55. package/src/plugins/SSEPlugin.ts +114 -0
  56. package/src/plugins/SessionPlugin.ts +98 -0
  57. package/src/plugins/StaticPlugin.ts +152 -0
  58. package/src/plugins/TimeoutPlugin.ts +33 -0
  59. package/src/plugins/index.ts +18 -0
  60. package/src/types/common.type.ts +82 -0
  61. package/src/types/config.type.ts +57 -0
  62. package/{dist/chunk-OWUGAI5V.mjs → src/types/http/status.ts} +49 -51
  63. package/src/types/index.ts +55 -0
  64. package/src/types/plugins/plugin.type.ts +170 -0
  65. package/src/types/reflect.d.ts +14 -0
  66. package/src/types/routes.type.ts +70 -0
  67. package/src/utils/HttpError.ts +62 -0
  68. package/src/utils/IpResolver.ts +30 -0
  69. package/src/utils/Logger.ts +144 -0
  70. package/src/utils/Parser.ts +182 -0
  71. package/src/utils/cookies/CookieManager.ts +48 -0
  72. package/src/utils/index.ts +9 -0
  73. package/{dist/chunk-UWIFSGSQ.mjs → src/utils/validators/DTOValidator.ts} +145 -141
  74. package/src/utils/validators/SchemaValidator.ts +45 -0
  75. package/dist/chunk-3UFAWS2V.js +0 -392
  76. package/dist/chunk-3UFAWS2V.js.map +0 -1
  77. package/dist/chunk-4LSFAAZW.js +0 -4
  78. package/dist/chunk-4LSFAAZW.js.map +0 -1
  79. package/dist/chunk-7NSRIVZM.js +0 -54
  80. package/dist/chunk-7NSRIVZM.js.map +0 -1
  81. package/dist/chunk-AOG6NYAM.js +0 -144
  82. package/dist/chunk-AOG6NYAM.js.map +0 -1
  83. package/dist/chunk-DR254CWJ.mjs.map +0 -1
  84. package/dist/chunk-EYAHUNC7.mjs.map +0 -1
  85. package/dist/chunk-HHDQPIJN.mjs +0 -19
  86. package/dist/chunk-HHDQPIJN.mjs.map +0 -1
  87. package/dist/chunk-HHZNAGGI.js +0 -702
  88. package/dist/chunk-HHZNAGGI.js.map +0 -1
  89. package/dist/chunk-KJM5XCAY.js +0 -21
  90. package/dist/chunk-KJM5XCAY.js.map +0 -1
  91. package/dist/chunk-NLSZKAPA.mjs +0 -1044
  92. package/dist/chunk-NLSZKAPA.mjs.map +0 -1
  93. package/dist/chunk-OWUGAI5V.mjs.map +0 -1
  94. package/dist/chunk-POPNQEOK.js +0 -1063
  95. package/dist/chunk-POPNQEOK.js.map +0 -1
  96. package/dist/chunk-QPRW4YU4.js +0 -134
  97. package/dist/chunk-QPRW4YU4.js.map +0 -1
  98. package/dist/chunk-REJDZUZ5.mjs +0 -382
  99. package/dist/chunk-REJDZUZ5.mjs.map +0 -1
  100. package/dist/chunk-TC6N6TJZ.mjs +0 -100
  101. package/dist/chunk-TC6N6TJZ.mjs.map +0 -1
  102. package/dist/chunk-TEUXKMXP.js +0 -122
  103. package/dist/chunk-TEUXKMXP.js.map +0 -1
  104. package/dist/chunk-UWIFSGSQ.mjs.map +0 -1
  105. package/dist/chunk-YPBKY4KY.mjs +0 -3
  106. package/dist/chunk-YPBKY4KY.mjs.map +0 -1
@@ -1,702 +0,0 @@
1
- 'use strict';
2
-
3
- var chunk3UFAWS2V_js = require('./chunk-3UFAWS2V.js');
4
- var http = require('http');
5
- var https = require('https');
6
- var fs = require('fs');
7
-
8
- // src/core/router.ts
9
- var PARAM_PREFIX = 58;
10
- function createNode(segment = "") {
11
- return {
12
- segment,
13
- children: /* @__PURE__ */ new Map(),
14
- paramChild: null,
15
- paramName: "",
16
- handlers: /* @__PURE__ */ new Map(),
17
- wildcardHandler: null
18
- };
19
- }
20
- var LRUCache = class {
21
- capacity;
22
- map;
23
- head;
24
- tail;
25
- constructor(capacity) {
26
- this.capacity = capacity;
27
- this.map = /* @__PURE__ */ new Map();
28
- this.head = { prev: null, next: null };
29
- this.tail = { prev: null, next: null };
30
- this.head.next = this.tail;
31
- this.tail.prev = this.head;
32
- }
33
- get(key) {
34
- const node = this.map.get(key);
35
- if (!node) return void 0;
36
- this.moveToHead(node);
37
- return node.value;
38
- }
39
- set(key, value) {
40
- const existing = this.map.get(key);
41
- if (existing) {
42
- existing.value = value;
43
- this.moveToHead(existing);
44
- return;
45
- }
46
- const node = { value, key, prev: null, next: null };
47
- this.map.set(key, node);
48
- this.addToHead(node);
49
- if (this.map.size > this.capacity) {
50
- const removed = this.removeTail();
51
- if (removed) this.map.delete(removed.key);
52
- }
53
- }
54
- addToHead(node) {
55
- node.prev = this.head;
56
- node.next = this.head.next;
57
- this.head.next.prev = node;
58
- this.head.next = node;
59
- }
60
- removeNode(node) {
61
- node.prev.next = node.next;
62
- node.next.prev = node.prev;
63
- }
64
- moveToHead(node) {
65
- this.removeNode(node);
66
- this.addToHead(node);
67
- }
68
- removeTail() {
69
- const node = this.tail.prev;
70
- if (node === this.head) return null;
71
- this.removeNode(node);
72
- return node;
73
- }
74
- clear() {
75
- this.map.clear();
76
- this.head.next = this.tail;
77
- this.tail.prev = this.head;
78
- }
79
- };
80
- var Router = class {
81
- root = createNode();
82
- cache;
83
- staticRoutes = /* @__PURE__ */ new Map();
84
- constructor(cacheSize = 1024) {
85
- this.cache = new LRUCache(cacheSize);
86
- }
87
- add(method, path, handler, middlewares = [], meta) {
88
- this.cache.clear();
89
- const normalizedPath = this.normalizePath(path);
90
- const stored = { handler, middlewares, meta };
91
- if (!normalizedPath.includes(":") && !normalizedPath.includes("*")) {
92
- const key = `${method}:${normalizedPath}`;
93
- this.staticRoutes.set(key, stored);
94
- return;
95
- }
96
- const segments = normalizedPath.split("/").filter(Boolean);
97
- let node = this.root;
98
- for (let i = 0; i < segments.length; i++) {
99
- const seg = segments[i];
100
- if (seg === "*") {
101
- if (!node.wildcardHandler) {
102
- node.wildcardHandler = /* @__PURE__ */ new Map();
103
- }
104
- node.wildcardHandler.set(method, stored);
105
- return;
106
- }
107
- if (seg.charCodeAt(0) === PARAM_PREFIX) {
108
- if (!node.paramChild) {
109
- node.paramChild = createNode(seg);
110
- node.paramChild.paramName = seg.slice(1);
111
- }
112
- node = node.paramChild;
113
- continue;
114
- }
115
- let child = node.children.get(seg);
116
- if (!child) {
117
- child = createNode(seg);
118
- node.children.set(seg, child);
119
- }
120
- node = child;
121
- }
122
- node.handlers.set(method, stored);
123
- }
124
- find(method, path) {
125
- const normalizedPath = this.normalizePath(path);
126
- const staticKey = `${method}:${normalizedPath}`;
127
- const staticRoute = this.staticRoutes.get(staticKey);
128
- if (staticRoute) {
129
- return {
130
- handler: staticRoute.handler,
131
- params: {},
132
- middlewares: staticRoute.middlewares,
133
- meta: staticRoute.meta
134
- };
135
- }
136
- const cacheKey = staticKey;
137
- const cached = this.cache.get(cacheKey);
138
- if (cached !== void 0) {
139
- return cached ? { ...cached, params: { ...cached.params } } : null;
140
- }
141
- const segments = normalizedPath.split("/").filter(Boolean);
142
- const params = {};
143
- const result = this.matchNode(this.root, segments, 0, params, method);
144
- if (result) {
145
- const match = {
146
- handler: result.handler,
147
- params,
148
- middlewares: result.middlewares,
149
- meta: result.meta
150
- };
151
- this.cache.set(cacheKey, match);
152
- return { ...match, params: { ...params } };
153
- }
154
- this.cache.set(cacheKey, null);
155
- return null;
156
- }
157
- matchNode(node, segments, idx, params, method) {
158
- if (idx === segments.length) {
159
- return node.handlers.get(method) ?? null;
160
- }
161
- const seg = segments[idx];
162
- const child = node.children.get(seg);
163
- if (child) {
164
- const result = this.matchNode(child, segments, idx + 1, params, method);
165
- if (result) return result;
166
- }
167
- if (node.paramChild) {
168
- params[node.paramChild.paramName] = seg;
169
- const result = this.matchNode(node.paramChild, segments, idx + 1, params, method);
170
- if (result) return result;
171
- delete params[node.paramChild.paramName];
172
- }
173
- if (node.wildcardHandler) {
174
- const route = node.wildcardHandler.get(method);
175
- if (route) return route;
176
- }
177
- return null;
178
- }
179
- normalizePath(path) {
180
- if (path === "/") return "/";
181
- if (path.endsWith("/") && path.length > 1) return path.slice(0, -1);
182
- return path;
183
- }
184
- getAllRoutes() {
185
- const routes = [];
186
- for (const [key] of this.staticRoutes) {
187
- const [method, path] = key.split(":", 2);
188
- routes.push({ method, path });
189
- }
190
- this.collectRoutes(this.root, "", routes);
191
- return routes;
192
- }
193
- collectRoutes(node, prefix, routes) {
194
- for (const [method] of node.handlers) {
195
- routes.push({ method, path: prefix || "/" });
196
- }
197
- for (const [seg, child] of node.children) {
198
- this.collectRoutes(child, `${prefix}/${seg}`, routes);
199
- }
200
- if (node.paramChild) {
201
- this.collectRoutes(
202
- node.paramChild,
203
- `${prefix}/:${node.paramChild.paramName}`,
204
- routes
205
- );
206
- }
207
- if (node.wildcardHandler) {
208
- for (const [method] of node.wildcardHandler) {
209
- routes.push({ method, path: `${prefix}/*` });
210
- }
211
- }
212
- }
213
- };
214
- var CONTROLLER_META_KEY = "azura:controller";
215
- var ROUTES_META_KEY = "azura:routes";
216
- var PARAMS_META_KEY = "azura:params";
217
- var AzuraServer = class {
218
- server = null;
219
- router;
220
- logger;
221
- middlewares = [];
222
- plugins = [];
223
- errorHandler = null;
224
- config;
225
- compiledChain = null;
226
- constructor(config = {}) {
227
- this.config = {
228
- environment: config.environment ?? process.env.NODE_ENV ?? "development",
229
- server: {
230
- port: config.server?.port ?? 3e3,
231
- host: config.server?.host ?? "0.0.0.0",
232
- keepAliveTimeout: config.server?.keepAliveTimeout ?? 72e3,
233
- headersTimeout: config.server?.headersTimeout ?? 75e3,
234
- requestTimeout: config.server?.requestTimeout ?? 3e4,
235
- ...config.server
236
- },
237
- logging: {
238
- enabled: config.logging?.enabled ?? true,
239
- level: config.logging?.level ?? "info",
240
- timestamp: config.logging?.timestamp ?? true,
241
- colors: config.logging?.colors ?? true,
242
- requestLogging: config.logging?.requestLogging ?? true,
243
- ...config.logging
244
- },
245
- plugins: config.plugins ?? {},
246
- debug: config.debug ?? false
247
- };
248
- this.router = new Router();
249
- this.logger = new chunk3UFAWS2V_js.Logger({
250
- level: this.config.logging?.enabled === false ? "silent" : this.config.logging?.level,
251
- colors: this.config.logging?.colors,
252
- timestamp: this.config.logging?.timestamp
253
- });
254
- }
255
- use(handler) {
256
- this.compiledChain = null;
257
- if (handler.length <= 2) {
258
- this.plugins.push(handler);
259
- } else {
260
- this.middlewares.push(handler);
261
- }
262
- return this;
263
- }
264
- plugin(handler) {
265
- this.compiledChain = null;
266
- this.plugins.push(handler);
267
- return this;
268
- }
269
- onError(handler) {
270
- this.errorHandler = handler;
271
- return this;
272
- }
273
- get(path, ...handlers) {
274
- return this.route("GET", path, handlers);
275
- }
276
- post(path, ...handlers) {
277
- return this.route("POST", path, handlers);
278
- }
279
- put(path, ...handlers) {
280
- return this.route("PUT", path, handlers);
281
- }
282
- delete(path, ...handlers) {
283
- return this.route("DELETE", path, handlers);
284
- }
285
- patch(path, ...handlers) {
286
- return this.route("PATCH", path, handlers);
287
- }
288
- head(path, ...handlers) {
289
- return this.route("HEAD", path, handlers);
290
- }
291
- options(path, ...handlers) {
292
- return this.route("OPTIONS", path, handlers);
293
- }
294
- all(path, ...handlers) {
295
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
296
- for (const method of methods) {
297
- this.route(method, path, handlers);
298
- }
299
- return this;
300
- }
301
- route(method, path, handlers) {
302
- const routeHandler = handlers[handlers.length - 1];
303
- const middlewares = handlers.slice(0, -1);
304
- this.router.add(method, path, routeHandler, middlewares);
305
- return this;
306
- }
307
- register(...controllers) {
308
- for (const Controller of controllers) {
309
- this.registerController(Controller);
310
- }
311
- return this;
312
- }
313
- registerController(Controller) {
314
- const instance = new Controller();
315
- const prefix = Reflect.getMetadata?.(CONTROLLER_META_KEY, Controller) ?? "";
316
- const controllerMiddlewares = Reflect.getMetadata?.("azura:middlewares", Controller) ?? [];
317
- const prototype = Controller.prototype;
318
- const propertyNames = Object.getOwnPropertyNames(prototype).filter(
319
- (p) => p !== "constructor"
320
- );
321
- for (const propertyKey of propertyNames) {
322
- const routeMeta = Reflect.getMetadata?.(
323
- ROUTES_META_KEY,
324
- prototype,
325
- propertyKey
326
- );
327
- if (!routeMeta) continue;
328
- const fullPath = this.joinPaths(prefix, routeMeta.path);
329
- const paramsMeta = Reflect.getMetadata?.(PARAMS_META_KEY, prototype, propertyKey) ?? [];
330
- const routeMiddlewares = Reflect.getMetadata?.("azura:middlewares", prototype, propertyKey) ?? [];
331
- const allMiddlewares = [...controllerMiddlewares, ...routeMiddlewares];
332
- const handler = async (req, res) => {
333
- const args = this.resolveParams(paramsMeta, req, res);
334
- const result = await instance[propertyKey](...args);
335
- if (result !== void 0 && !res.sent) {
336
- if (typeof result === "object") {
337
- res.json(result);
338
- } else {
339
- res.send(String(result));
340
- }
341
- }
342
- };
343
- this.router.add(routeMeta.method, fullPath, handler, allMiddlewares, routeMeta.meta);
344
- }
345
- }
346
- resolveParams(paramsMeta, req, res) {
347
- if (!paramsMeta || paramsMeta.length === 0) return [req, res];
348
- const sorted = [...paramsMeta].sort((a, b) => a.index - b.index);
349
- const args = new Array(sorted.length);
350
- for (const meta of sorted) {
351
- let value;
352
- switch (meta.type) {
353
- case "body":
354
- value = meta.name ? req.body?.[meta.name] : req.body;
355
- break;
356
- case "query":
357
- value = meta.name ? req.query[meta.name] : req.query;
358
- break;
359
- case "param":
360
- value = meta.name ? req.params[meta.name] : req.params;
361
- break;
362
- case "header":
363
- value = meta.name ? req.headers[meta.name.toLowerCase()] : req.headers;
364
- break;
365
- case "cookie":
366
- value = meta.name ? req.cookies[meta.name] : req.cookies;
367
- break;
368
- case "req":
369
- value = req;
370
- break;
371
- case "res":
372
- value = res;
373
- break;
374
- case "next":
375
- value = () => {
376
- };
377
- break;
378
- case "ip":
379
- value = req.ip;
380
- break;
381
- case "session":
382
- value = req.session;
383
- break;
384
- default:
385
- value = void 0;
386
- }
387
- if (meta.pipes) {
388
- for (const pipe of meta.pipes) {
389
- value = pipe(value);
390
- }
391
- }
392
- args[meta.index] = value;
393
- }
394
- return args;
395
- }
396
- joinPaths(prefix, path) {
397
- const p = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
398
- const s = path.startsWith("/") ? path : `/${path}`;
399
- return `${p}${s}`;
400
- }
401
- extendRequest(req, pathname, query) {
402
- const azReq = req;
403
- azReq.pathname = pathname;
404
- azReq.query = query;
405
- azReq.params = {};
406
- azReq.cookies = chunk3UFAWS2V_js.parseCookies(req.headers.cookie);
407
- azReq.ip = chunk3UFAWS2V_js.resolveIp(req);
408
- azReq.protocol = req.socket.encrypted ? "https" : "http";
409
- azReq.secure = azReq.protocol === "https";
410
- azReq.hostname = (req.headers.host ?? "localhost").split(":")[0];
411
- azReq.startTime = process.hrtime.bigint();
412
- azReq.raw = req;
413
- return azReq;
414
- }
415
- extendResponse(res) {
416
- const azRes = res;
417
- azRes.locals = {};
418
- azRes.sent = false;
419
- azRes.status = function(code) {
420
- this.statusCode = code;
421
- return this;
422
- };
423
- azRes.json = function(data) {
424
- if (this.sent) return;
425
- this.sent = true;
426
- const body = JSON.stringify(data);
427
- this.setHeader("Content-Type", "application/json; charset=utf-8");
428
- this.setHeader("Content-Length", Buffer.byteLength(body));
429
- this.end(body);
430
- };
431
- azRes.send = function(body) {
432
- if (this.sent) return;
433
- this.sent = true;
434
- if (!this.getHeader("Content-Type")) {
435
- this.setHeader("Content-Type", typeof body === "string" ? "text/plain; charset=utf-8" : "application/octet-stream");
436
- }
437
- const buf = typeof body === "string" ? Buffer.from(body) : body;
438
- this.setHeader("Content-Length", buf.length);
439
- this.end(buf);
440
- };
441
- azRes.html = function(body) {
442
- if (this.sent) return;
443
- this.sent = true;
444
- this.setHeader("Content-Type", "text/html; charset=utf-8");
445
- this.setHeader("Content-Length", Buffer.byteLength(body));
446
- this.end(body);
447
- };
448
- azRes.redirect = function(url, code = 302) {
449
- if (this.sent) return;
450
- this.sent = true;
451
- this.statusCode = code;
452
- this.setHeader("Location", url);
453
- this.end();
454
- };
455
- azRes.cookie = function(name, value, options) {
456
- const header = chunk3UFAWS2V_js.serializeCookie(name, value, options);
457
- const existing = this.getHeader("Set-Cookie");
458
- if (existing) {
459
- const arr = Array.isArray(existing) ? existing : [String(existing)];
460
- arr.push(header);
461
- this.setHeader("Set-Cookie", arr);
462
- } else {
463
- this.setHeader("Set-Cookie", header);
464
- }
465
- return this;
466
- };
467
- azRes.clearCookie = function(name, options) {
468
- const header = chunk3UFAWS2V_js.clearCookieHeader(name, options);
469
- const existing = this.getHeader("Set-Cookie");
470
- if (existing) {
471
- const arr = Array.isArray(existing) ? existing : [String(existing)];
472
- arr.push(header);
473
- this.setHeader("Set-Cookie", arr);
474
- } else {
475
- this.setHeader("Set-Cookie", header);
476
- }
477
- return this;
478
- };
479
- azRes.header = function(name, value) {
480
- this.setHeader(name, value);
481
- return this;
482
- };
483
- azRes.type = function(contentType) {
484
- this.setHeader("Content-Type", contentType);
485
- return this;
486
- };
487
- azRes.attachment = function(filename) {
488
- if (filename) {
489
- this.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
490
- } else {
491
- this.setHeader("Content-Disposition", "attachment");
492
- }
493
- return this;
494
- };
495
- azRes.download = function(_path, _filename) {
496
- };
497
- return azRes;
498
- }
499
- compileMiddlewareChain() {
500
- if (this.compiledChain) return this.compiledChain;
501
- const self = this;
502
- const globalMiddlewares = [...this.middlewares];
503
- this.compiledChain = async (req, res) => {
504
- for (const plugin of self.plugins) {
505
- if (res.sent) return;
506
- await new Promise((resolve, reject) => {
507
- try {
508
- const result = plugin({ req, res }, (err) => {
509
- if (err) reject(err);
510
- else resolve();
511
- });
512
- if (result && typeof result.then === "function") {
513
- result.then(resolve, reject);
514
- }
515
- } catch (e) {
516
- reject(e);
517
- }
518
- });
519
- }
520
- if (res.sent) return;
521
- let idx = 0;
522
- const runMiddleware = async () => {
523
- if (idx >= globalMiddlewares.length || res.sent) return;
524
- const mw = globalMiddlewares[idx++];
525
- await new Promise((resolve, reject) => {
526
- try {
527
- const result = mw(req, res, (err) => {
528
- if (err) reject(err);
529
- else resolve();
530
- });
531
- if (result && typeof result.then === "function") {
532
- result.then(resolve, reject);
533
- }
534
- } catch (e) {
535
- reject(e);
536
- }
537
- });
538
- await runMiddleware();
539
- };
540
- await runMiddleware();
541
- };
542
- return this.compiledChain;
543
- }
544
- async handleRequest(req, res) {
545
- const { pathname, search } = chunk3UFAWS2V_js.parseUrl(req.url ?? "/");
546
- const query = chunk3UFAWS2V_js.parseQueryString(search);
547
- const azReq = this.extendRequest(req, pathname, query);
548
- const azRes = this.extendResponse(res);
549
- try {
550
- const chain = this.compileMiddlewareChain();
551
- await chain(azReq, azRes);
552
- if (azRes.sent) return;
553
- const method = (req.method ?? "GET").toUpperCase();
554
- const match = this.router.find(method, pathname);
555
- if (!match) {
556
- if (pathname === "/favicon.ico") {
557
- azRes.status(204).send("");
558
- return;
559
- }
560
- throw chunk3UFAWS2V_js.HttpError.notFound(`Route ${method} ${pathname} not found`);
561
- }
562
- azReq.params = match.params;
563
- if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
564
- azReq.body = await chunk3UFAWS2V_js.parseBody(req);
565
- }
566
- for (const mw of match.middlewares) {
567
- if (azRes.sent) return;
568
- await new Promise((resolve, reject) => {
569
- try {
570
- const result2 = mw(azReq, azRes, (err) => {
571
- if (err) reject(err);
572
- else resolve();
573
- });
574
- if (result2 && typeof result2.then === "function") {
575
- result2.then(resolve, reject);
576
- }
577
- } catch (e) {
578
- reject(e);
579
- }
580
- });
581
- }
582
- if (azRes.sent) return;
583
- const result = await match.handler(azReq, azRes);
584
- if (result !== void 0 && !azRes.sent) {
585
- if (typeof result === "object" && result !== null) {
586
- azRes.json(result);
587
- } else {
588
- azRes.send(String(result));
589
- }
590
- }
591
- } catch (err) {
592
- this.handleError(err, azReq, azRes);
593
- } finally {
594
- if (this.config.logging?.requestLogging) {
595
- const duration = process.hrtime.bigint() - azReq.startTime;
596
- this.logger.request(
597
- req.method ?? "GET",
598
- pathname,
599
- res.statusCode,
600
- duration
601
- );
602
- }
603
- }
604
- }
605
- handleError(err, req, res) {
606
- if (res.sent) return;
607
- if (this.errorHandler) {
608
- try {
609
- this.errorHandler(err, req, res, () => {
610
- });
611
- return;
612
- } catch (handlerErr) {
613
- this.logger.error("Error handler threw:", handlerErr);
614
- }
615
- }
616
- if (err instanceof chunk3UFAWS2V_js.HttpError) {
617
- res.status(err.statusCode).json(err.toJSON());
618
- return;
619
- }
620
- const statusCode = err?.statusCode ?? err?.status ?? 500;
621
- const message = this.config.environment === "production" ? "Internal Server Error" : err?.message ?? "Internal Server Error";
622
- this.logger.error(`Unhandled error: ${err?.message ?? err}`);
623
- if (this.config.debug && err?.stack) {
624
- this.logger.error(err.stack);
625
- }
626
- res.status(statusCode).json({
627
- error: {
628
- statusCode,
629
- message,
630
- ...this.config.debug ? { stack: err?.stack } : {}
631
- }
632
- });
633
- }
634
- async listen(port, callback) {
635
- const serverPort = port ?? this.config.server?.port ?? 3e3;
636
- const host = this.config.server?.host ?? "0.0.0.0";
637
- const handler = (req, res) => {
638
- this.handleRequest(req, res).catch((err) => {
639
- this.logger.error("Fatal request error:", err);
640
- if (!res.headersSent) {
641
- res.statusCode = 500;
642
- res.end('{"error":{"statusCode":500,"message":"Internal Server Error"}}');
643
- }
644
- });
645
- };
646
- if (this.config.server?.https) {
647
- const httpsConfig = this.config.server.https;
648
- this.server = https.createServer(
649
- {
650
- key: fs.readFileSync(httpsConfig.key),
651
- cert: fs.readFileSync(httpsConfig.cert),
652
- ...httpsConfig.ca ? { ca: fs.readFileSync(httpsConfig.ca) } : {}
653
- },
654
- handler
655
- );
656
- } else {
657
- this.server = http.createServer(handler);
658
- }
659
- if (this.config.server?.keepAliveTimeout) {
660
- this.server.keepAliveTimeout = this.config.server.keepAliveTimeout;
661
- }
662
- if (this.config.server?.headersTimeout) {
663
- this.server.headersTimeout = this.config.server.headersTimeout;
664
- }
665
- return new Promise((resolve) => {
666
- this.server.listen(serverPort, host, () => {
667
- this.logger.banner(serverPort, host);
668
- callback?.();
669
- resolve(this.server);
670
- });
671
- });
672
- }
673
- async close() {
674
- return new Promise((resolve, reject) => {
675
- if (!this.server) {
676
- resolve();
677
- return;
678
- }
679
- this.server.close((err) => {
680
- if (err) reject(err);
681
- else resolve();
682
- });
683
- });
684
- }
685
- getRouter() {
686
- return this.router;
687
- }
688
- getLogger() {
689
- return this.logger;
690
- }
691
- getConfig() {
692
- return this.config;
693
- }
694
- getRoutes() {
695
- return this.router.getAllRoutes();
696
- }
697
- };
698
-
699
- exports.AzuraServer = AzuraServer;
700
- exports.Router = Router;
701
- //# sourceMappingURL=chunk-HHZNAGGI.js.map
702
- //# sourceMappingURL=chunk-HHZNAGGI.js.map