tezx 1.0.2 → 1.0.4

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.mjs CHANGED
@@ -1,11 +1,16 @@
1
- import{createRequire as _pkgrollCR}from"node:module";const require=_pkgrollCR(import.meta.url);let GlobalConfig = class {
1
+ import { createRequire as _pkgrollCR } from "node:module";
2
+ const require = _pkgrollCR(import.meta.url);
3
+ let GlobalConfig = class {
2
4
  static notFound = (ctx2) => {
3
5
  const {
4
6
  method,
5
- urlRef: { pathname }
7
+ urlRef: { pathname },
6
8
  } = ctx2.req;
7
- return ctx2.text(`${method}: '${pathname}' could not find
8
- `, 404);
9
+ return ctx2.text(
10
+ `${method}: '${pathname}' could not find
11
+ `,
12
+ 404,
13
+ );
9
14
  };
10
15
  static onError = (err, ctx2) => {
11
16
  return ctx2.text(err, 500);
@@ -27,7 +32,7 @@ function denoAdapter(TezX2) {
27
32
  return new Response(response.body, {
28
33
  status: response.status,
29
34
  statusText: response.statusText || "",
30
- headers: new Headers(response.headers)
35
+ headers: new Headers(response.headers),
31
36
  });
32
37
  }
33
38
  }
@@ -54,7 +59,7 @@ function denoAdapter(TezX2) {
54
59
  }
55
60
  }
56
61
  return {
57
- listen
62
+ listen,
58
63
  };
59
64
  }
60
65
  function bunAdapter(TezX2) {
@@ -74,10 +79,10 @@ function bunAdapter(TezX2) {
74
79
  return new Response(response.body, {
75
80
  status: response.status,
76
81
  statusText: response.statusText || "",
77
- headers: new Headers(response.headers)
82
+ headers: new Headers(response.headers),
78
83
  });
79
84
  }
80
- }
85
+ },
81
86
  });
82
87
  const protocol = "\x1B[1;34mhttp\x1B[0m";
83
88
  const message = `\x1B[1m Bun TezX Server running at ${protocol}://localhost:${port}/\x1B[0m`;
@@ -95,50 +100,52 @@ function bunAdapter(TezX2) {
95
100
  }
96
101
  }
97
102
  return {
98
- listen
103
+ listen,
99
104
  };
100
105
  }
101
106
  function nodeAdapter(TezX2) {
102
107
  function listen(port, callback) {
103
- import('http').then((r) => {
104
- let server = r.createServer(async (req, res) => {
105
- const response = await TezX2.serve(req);
106
- const statusText = response?.statusText;
107
- if (!(response instanceof Response)) {
108
- throw new Error("Invalid response from TezX.serve");
109
- }
110
- const headers = Object.fromEntries(await response.headers.entries());
111
- if (statusText) {
112
- res.statusMessage = statusText;
113
- }
114
- res.writeHead(response.status, headers);
115
- const { Readable } = await import('stream');
116
- if (response.body instanceof Readable) {
117
- response.body.pipe(res);
118
- } else {
119
- const body = await response.arrayBuffer();
120
- res.end(Buffer.from(body));
121
- }
122
- });
123
- server.listen(port, () => {
124
- const protocol = "\x1B[1;34mhttp\x1B[0m";
125
- const message = `\x1B[1m NodeJS TezX Server running at ${protocol}://localhost:${port}/\x1B[0m`;
126
- if (typeof callback == "function") {
127
- callback(message);
128
- } else {
129
- const logger = GlobalConfig.loggerFn();
130
- if (logger.success) {
131
- logger.success(message);
108
+ import("http")
109
+ .then((r) => {
110
+ let server = r.createServer(async (req, res) => {
111
+ const response = await TezX2.serve(req);
112
+ const statusText = response?.statusText;
113
+ if (!(response instanceof Response)) {
114
+ throw new Error("Invalid response from TezX.serve");
132
115
  }
133
- }
134
- return server;
116
+ const headers = Object.fromEntries(await response.headers.entries());
117
+ if (statusText) {
118
+ res.statusMessage = statusText;
119
+ }
120
+ res.writeHead(response.status, headers);
121
+ const { Readable } = await import("stream");
122
+ if (response.body instanceof Readable) {
123
+ response.body.pipe(res);
124
+ } else {
125
+ const body = await response.arrayBuffer();
126
+ res.end(Buffer.from(body));
127
+ }
128
+ });
129
+ server.listen(port, () => {
130
+ const protocol = "\x1B[1;34mhttp\x1B[0m";
131
+ const message = `\x1B[1m NodeJS TezX Server running at ${protocol}://localhost:${port}/\x1B[0m`;
132
+ if (typeof callback == "function") {
133
+ callback(message);
134
+ } else {
135
+ const logger = GlobalConfig.loggerFn();
136
+ if (logger.success) {
137
+ logger.success(message);
138
+ }
139
+ }
140
+ return server;
141
+ });
142
+ })
143
+ .catch((r) => {
144
+ throw Error(r.message);
135
145
  });
136
- }).catch((r) => {
137
- throw Error(r.message);
138
- });
139
146
  }
140
147
  return {
141
- listen
148
+ listen,
142
149
  };
143
150
  }
144
151
 
@@ -284,7 +291,7 @@ const mimeTypes = {
284
291
  ai: "application/postscript",
285
292
  swf: "application/x-shockwave-flash",
286
293
  jar: "application/java-archive",
287
- gcode: "text/x.gcode"
294
+ gcode: "text/x.gcode",
288
295
  };
289
296
  const defaultMimeType = "application/octet-stream";
290
297
  async function getFiles(dir, basePath = "/", ref, option) {
@@ -295,36 +302,36 @@ async function getFiles(dir, basePath = "/", ref, option) {
295
302
  const path = `${dir}/${entry.name}`;
296
303
  if (entry.isDirectory) {
297
304
  files.push(
298
- ...await getFiles(path, `${basePath}/${entry.name}`, ref, option)
305
+ ...(await getFiles(path, `${basePath}/${entry.name}`, ref, option)),
299
306
  );
300
307
  } else {
301
308
  const x = `${basePath}/${entry.name}`;
302
309
  files.push({
303
310
  file: path,
304
- path: x.replace(/\\/g, "/")
311
+ path: x.replace(/\\/g, "/"),
305
312
  });
306
313
  }
307
314
  }
308
315
  } else {
309
- const fs = await import('fs/promises');
310
- const path = await import('path');
316
+ const fs = await import("fs/promises");
317
+ const path = await import("path");
311
318
  const entries = await fs.readdir(dir, { withFileTypes: true });
312
319
  for (const entry of entries) {
313
320
  const fullPath = path.join(dir, entry.name);
314
321
  if (entry.isDirectory()) {
315
322
  files.push(
316
- ...await getFiles(
323
+ ...(await getFiles(
317
324
  fullPath,
318
325
  `${basePath}/${entry.name}`,
319
326
  ref,
320
- option
321
- )
327
+ option,
328
+ )),
322
329
  );
323
330
  } else {
324
331
  const path2 = `${basePath}/${entry.name}`;
325
332
  files.push({
326
333
  file: fullPath,
327
- path: path2.replace(/\\/g, "/")
334
+ path: path2.replace(/\\/g, "/"),
328
335
  });
329
336
  }
330
337
  }
@@ -347,7 +354,7 @@ class TezResponse {
347
354
  static json(body, ...args) {
348
355
  let status = 200;
349
356
  let headers = {
350
- "Content-Type": "application/json; charset=utf-8"
357
+ "Content-Type": "application/json; charset=utf-8",
351
358
  };
352
359
  if (typeof args[0] === "number") {
353
360
  status = args[0];
@@ -359,13 +366,13 @@ class TezResponse {
359
366
  }
360
367
  return new Response(JSON.stringify(body), {
361
368
  status,
362
- headers
369
+ headers,
363
370
  });
364
371
  }
365
372
  static html(data, ...args) {
366
373
  let status = 200;
367
374
  let headers = {
368
- "Content-Type": "text/html; charset=utf-8"
375
+ "Content-Type": "text/html; charset=utf-8",
369
376
  };
370
377
  if (typeof args[0] === "number") {
371
378
  status = args[0];
@@ -377,13 +384,13 @@ class TezResponse {
377
384
  }
378
385
  return new Response(data, {
379
386
  status,
380
- headers
387
+ headers,
381
388
  });
382
389
  }
383
390
  static text(data, ...args) {
384
391
  let status = 200;
385
392
  let headers = {
386
- "Content-Type": "text/plain; charset=utf-8"
393
+ "Content-Type": "text/plain; charset=utf-8",
387
394
  };
388
395
  if (typeof args[0] === "number") {
389
396
  status = args[0];
@@ -395,13 +402,13 @@ class TezResponse {
395
402
  }
396
403
  return new Response(data, {
397
404
  status,
398
- headers
405
+ headers,
399
406
  });
400
407
  }
401
408
  static xml(data, ...args) {
402
409
  let status = 200;
403
410
  let headers = {
404
- "Content-Type": "application/xml; charset=utf-8"
411
+ "Content-Type": "application/xml; charset=utf-8",
405
412
  };
406
413
  if (typeof args[0] === "number") {
407
414
  status = args[0];
@@ -413,7 +420,7 @@ class TezResponse {
413
420
  }
414
421
  return new Response(data, {
415
422
  status,
416
- headers
423
+ headers,
417
424
  });
418
425
  }
419
426
  static send(body, ...args) {
@@ -439,7 +446,7 @@ class TezResponse {
439
446
  }
440
447
  return new Response(body, {
441
448
  status,
442
- headers
449
+ headers,
443
450
  });
444
451
  }
445
452
  /**
@@ -452,7 +459,7 @@ class TezResponse {
452
459
  static redirect(url, status = 302, headers) {
453
460
  return new Response(null, {
454
461
  status,
455
- headers: { Location: url }
462
+ headers: { Location: url },
456
463
  });
457
464
  }
458
465
  /**
@@ -466,7 +473,7 @@ class TezResponse {
466
473
  let fileExists = false;
467
474
  const runtime = EnvironmentDetector.getEnvironment;
468
475
  if (runtime === "node") {
469
- const { existsSync } = await import('fs');
476
+ const { existsSync } = await import("fs");
470
477
  fileExists = existsSync(filePath);
471
478
  } else if (runtime === "bun") {
472
479
  fileExists = Bun.file(filePath).exists();
@@ -483,10 +490,12 @@ class TezResponse {
483
490
  }
484
491
  let fileBuffer;
485
492
  if (runtime === "node") {
486
- const { readFileSync } = await import('fs');
493
+ const { readFileSync } = await import("fs");
487
494
  fileBuffer = await readFileSync(filePath);
488
495
  } else if (runtime === "bun") {
489
- fileBuffer = await Bun.file(filePath).arrayBuffer().then((buf) => new Uint8Array(buf));
496
+ fileBuffer = await Bun.file(filePath)
497
+ .arrayBuffer()
498
+ .then((buf) => new Uint8Array(buf));
490
499
  } else if (runtime === "deno") {
491
500
  fileBuffer = await Deno.readFile(filePath);
492
501
  }
@@ -495,8 +504,8 @@ class TezResponse {
495
504
  headers: {
496
505
  "Content-Disposition": `attachment; filename="${fileName}"`,
497
506
  "Content-Type": "application/octet-stream",
498
- "Content-Length": fileBuffer.byteLength.toString()
499
- }
507
+ "Content-Length": fileBuffer.byteLength.toString(),
508
+ },
500
509
  });
501
510
  } catch (error) {
502
511
  throw Error("Internal Server Error" + error?.message);
@@ -508,7 +517,7 @@ class TezResponse {
508
517
  const resolvedPath = filePath;
509
518
  let fileExists = false;
510
519
  if (runtime === "node") {
511
- const { existsSync } = await import('fs');
520
+ const { existsSync } = await import("fs");
512
521
  fileExists = existsSync(resolvedPath);
513
522
  } else if (runtime === "bun") {
514
523
  fileExists = Bun.file(resolvedPath).exists();
@@ -525,7 +534,7 @@ class TezResponse {
525
534
  }
526
535
  let fileSize = 0;
527
536
  if (runtime === "node") {
528
- const { statSync } = await import('fs');
537
+ const { statSync } = await import("fs");
529
538
  fileSize = statSync(resolvedPath).size;
530
539
  } else if (runtime === "bun") {
531
540
  fileSize = (await Bun.file(resolvedPath).arrayBuffer()).byteLength;
@@ -537,7 +546,7 @@ class TezResponse {
537
546
  const mimeType = mimeTypes[ext] || defaultMimeType;
538
547
  let fileStream;
539
548
  if (runtime === "node") {
540
- const { createReadStream } = await import('fs');
549
+ const { createReadStream } = await import("fs");
541
550
  fileStream = createReadStream(resolvedPath);
542
551
  } else if (runtime === "bun") {
543
552
  fileStream = Bun.file(resolvedPath).stream();
@@ -547,7 +556,7 @@ class TezResponse {
547
556
  }
548
557
  let headers = {
549
558
  "Content-Type": mimeType,
550
- "Content-Length": fileSize.toString()
559
+ "Content-Length": fileSize.toString(),
551
560
  };
552
561
  let fileName = "";
553
562
  if (typeof args[0] === "string") {
@@ -563,7 +572,7 @@ class TezResponse {
563
572
  }
564
573
  return new Response(fileStream, {
565
574
  status: 200,
566
- headers
575
+ headers,
567
576
  });
568
577
  } catch (error) {
569
578
  throw Error("Internal Server Error" + error?.message);
@@ -594,11 +603,15 @@ class CommonHandler {
594
603
  }
595
604
 
596
605
  function sanitizePathSplit(basePath, path) {
597
- const parts = `${basePath}/${path}`.replace(/\\/g, "")?.split("/").filter(Boolean);
606
+ const parts = `${basePath}/${path}`
607
+ .replace(/\\/g, "")
608
+ ?.split("/")
609
+ .filter(Boolean);
598
610
  return parts;
599
611
  }
600
612
  function urlParse(url) {
601
- const urlPattern = /^(?:(\w+):\/\/)?(?:([^:@]+)?(?::([^@]+))?@)?([^:/?#]+)?(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;
613
+ const urlPattern =
614
+ /^(?:(\w+):\/\/)?(?:([^:@]+)?(?::([^@]+))?@)?([^:/?#]+)?(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;
602
615
  let matches = url.match(urlPattern);
603
616
  const [
604
617
  _,
@@ -609,7 +622,7 @@ function urlParse(url) {
609
622
  port,
610
623
  path,
611
624
  queryString,
612
- hash
625
+ hash,
613
626
  ] = matches;
614
627
  let origin = hostname;
615
628
  if (protocol) {
@@ -624,15 +637,13 @@ function urlParse(url) {
624
637
  if (queryString) {
625
638
  const queryPart = decodeURIComponent(queryString);
626
639
  const keyValuePairs = queryPart.split("&");
627
- const paramsObj = keyValuePairs?.map(
628
- (keyValue) => {
629
- const [key, value] = keyValue.split("=");
630
- return {
631
- [key]: value
632
- };
633
- }
634
- );
635
- return paramsObj.reduce(function(total, value) {
640
+ const paramsObj = keyValuePairs?.map((keyValue) => {
641
+ const [key, value] = keyValue.split("=");
642
+ return {
643
+ [key]: value,
644
+ };
645
+ });
646
+ return paramsObj.reduce(function (total, value) {
636
647
  return { ...total, ...value };
637
648
  }, {});
638
649
  } else {
@@ -649,7 +660,7 @@ function urlParse(url) {
649
660
  hostname,
650
661
  href: url,
651
662
  port,
652
- query: query()
663
+ query: query(),
653
664
  };
654
665
  }
655
666
 
@@ -761,7 +772,7 @@ class Router extends MiddlewareConfigure {
761
772
  break;
762
773
  default:
763
774
  throw new Error(
764
- `\x1B[1;31m404 Not Found\x1B[0m \x1B[1;32mInvalid arguments\x1B[0m`
775
+ `\x1B[1;31m404 Not Found\x1B[0m \x1B[1;32mInvalid arguments\x1B[0m`,
765
776
  );
766
777
  }
767
778
  getFiles(dir, route, this, options);
@@ -830,7 +841,7 @@ class Router extends MiddlewareConfigure {
830
841
  */
831
842
  group(prefix, callback) {
832
843
  const router = new Router({
833
- basePath: prefix
844
+ basePath: prefix,
834
845
  // env: this.env
835
846
  });
836
847
  callback(router);
@@ -893,7 +904,7 @@ class Router extends MiddlewareConfigure {
893
904
  }
894
905
  if (!middlewares.every((middleware) => typeof middleware === "function")) {
895
906
  throw new Error(
896
- "Middleware must be a function or an array of functions."
907
+ "Middleware must be a function or an array of functions.",
897
908
  );
898
909
  }
899
910
  this.#addRoute(method, path, callback, middlewares);
@@ -911,7 +922,7 @@ class Router extends MiddlewareConfigure {
911
922
  handler = /* @__PURE__ */ new Map();
912
923
  handler.set(method, {
913
924
  callback,
914
- middlewares: finalMiddleware
925
+ middlewares: finalMiddleware,
915
926
  });
916
927
  return this.routers.set(p, handler);
917
928
  }
@@ -939,7 +950,7 @@ class Router extends MiddlewareConfigure {
939
950
  if (!GlobalConfig.overwriteMethod && node.handlers.has(method)) return;
940
951
  node.handlers.set(method, {
941
952
  callback,
942
- middlewares: finalMiddleware
953
+ middlewares: finalMiddleware,
943
954
  });
944
955
  node.pathname = path;
945
956
  }
@@ -1055,9 +1066,7 @@ class Router extends MiddlewareConfigure {
1055
1066
  if (n.children.has(path)) {
1056
1067
  let findNode = n.children.get(path);
1057
1068
  if (GlobalConfig.allowDuplicateMw) {
1058
- findNode.middlewares.push(
1059
- ...middlewareNode.middlewares
1060
- );
1069
+ findNode.middlewares.push(...middlewareNode.middlewares);
1061
1070
  } else {
1062
1071
  for (const mw of middlewareNode.middlewares) {
1063
1072
  if (findNode.middlewares.has(mw)) {
@@ -1075,9 +1084,7 @@ class Router extends MiddlewareConfigure {
1075
1084
  }
1076
1085
  }
1077
1086
  if (GlobalConfig.allowDuplicateMw) {
1078
- rootMiddlewares.middlewares.push(
1079
- ...routerMiddlewares.middlewares
1080
- );
1087
+ rootMiddlewares.middlewares.push(...routerMiddlewares.middlewares);
1081
1088
  } else {
1082
1089
  for (const mw of routerMiddlewares.middlewares) {
1083
1090
  if (rootMiddlewares.middlewares.has(mw)) {
@@ -1331,40 +1338,53 @@ async function parseMultipartBody(req, boundary, options) {
1331
1338
  const fieldName = fieldNameMatch[1];
1332
1339
  const contentType = contentTypeMatch[1];
1333
1340
  if (options?.sanitized) {
1334
- filename = `${Date.now()}-${filename.replace(/\s+/g, "")?.replace(/[^a-zA-Z0-9.-]/g, "-")}`?.toLowerCase();
1341
+ filename =
1342
+ `${Date.now()}-${filename.replace(/\s+/g, "")?.replace(/[^a-zA-Z0-9.-]/g, "-")}`?.toLowerCase();
1335
1343
  }
1336
- if (Array.isArray(options?.allowedTypes) && !options.allowedTypes?.includes(contentType)) {
1344
+ if (
1345
+ Array.isArray(options?.allowedTypes) &&
1346
+ !options.allowedTypes?.includes(contentType)
1347
+ ) {
1337
1348
  reject(
1338
- `Invalid file type: "${contentType}". Allowed types: ${options.allowedTypes.join(", ")}`
1349
+ `Invalid file type: "${contentType}". Allowed types: ${options.allowedTypes.join(", ")}`,
1339
1350
  );
1340
1351
  }
1341
1352
  const fileContentStartIndex = part.indexOf("\r\n\r\n") + 4;
1342
1353
  const fileContent = Buffer.from(
1343
1354
  part.substring(fileContentStartIndex),
1344
- "binary"
1355
+ "binary",
1345
1356
  );
1346
1357
  const arrayBuffer = fileContent.buffer.slice(
1347
1358
  fileContent.byteOffset,
1348
- fileContent.byteOffset + fileContent.byteLength
1359
+ fileContent.byteOffset + fileContent.byteLength,
1349
1360
  );
1350
- if (typeof options?.maxSize !== "undefined" && fileContent.byteLength > options.maxSize) {
1361
+ if (
1362
+ typeof options?.maxSize !== "undefined" &&
1363
+ fileContent.byteLength > options.maxSize
1364
+ ) {
1351
1365
  reject(
1352
- `File size exceeds the limit: ${fileContent.byteLength} bytes (Max: ${options.maxSize} bytes)`
1366
+ `File size exceeds the limit: ${fileContent.byteLength} bytes (Max: ${options.maxSize} bytes)`,
1353
1367
  );
1354
1368
  }
1355
1369
  const file = new File([arrayBuffer], filename, {
1356
- type: contentType
1370
+ type: contentType,
1357
1371
  });
1358
- if (typeof options?.maxFiles != "undefined" && options.maxFiles == 0) {
1372
+ if (
1373
+ typeof options?.maxFiles != "undefined" &&
1374
+ options.maxFiles == 0
1375
+ ) {
1359
1376
  reject(
1360
- `Field "${fieldName}" exceeds the maximum allowed file count of ${options.maxFiles}.`
1377
+ `Field "${fieldName}" exceeds the maximum allowed file count of ${options.maxFiles}.`,
1361
1378
  );
1362
1379
  }
1363
1380
  if (formDataField[fieldName]) {
1364
1381
  if (Array.isArray(formDataField[fieldName])) {
1365
- if (typeof options?.maxFiles != "undefined" && formDataField[fieldName]?.length >= options.maxFiles) {
1382
+ if (
1383
+ typeof options?.maxFiles != "undefined" &&
1384
+ formDataField[fieldName]?.length >= options.maxFiles
1385
+ ) {
1366
1386
  reject(
1367
- `Field "${fieldName}" exceeds the maximum allowed file count of ${options.maxFiles}.`
1387
+ `Field "${fieldName}" exceeds the maximum allowed file count of ${options.maxFiles}.`,
1368
1388
  );
1369
1389
  }
1370
1390
  formDataField[fieldName].push(file);
@@ -1378,8 +1398,7 @@ async function parseMultipartBody(req, boundary, options) {
1378
1398
  }
1379
1399
  }
1380
1400
  resolve(formDataField);
1381
- } catch {
1382
- }
1401
+ } catch {}
1383
1402
  });
1384
1403
  });
1385
1404
  } else if (runtime === "deno" || runtime === "bun") {
@@ -1390,32 +1409,43 @@ async function parseMultipartBody(req, boundary, options) {
1390
1409
  if (val instanceof File && typeof options == "object") {
1391
1410
  let filename = val.name;
1392
1411
  if (options?.sanitized) {
1393
- filename = `${Date.now()}-${filename.replace(/\s+/g, "")?.replace(/[^a-zA-Z0-9.-]/g, "-")}`?.toLowerCase();
1412
+ filename =
1413
+ `${Date.now()}-${filename.replace(/\s+/g, "")?.replace(/[^a-zA-Z0-9.-]/g, "-")}`?.toLowerCase();
1394
1414
  }
1395
- if (Array.isArray(options?.allowedTypes) && !options.allowedTypes?.includes(val.type)) {
1415
+ if (
1416
+ Array.isArray(options?.allowedTypes) &&
1417
+ !options.allowedTypes?.includes(val.type)
1418
+ ) {
1396
1419
  throw new Error(
1397
- `Invalid file type: "${val.type}". Allowed types: ${options.allowedTypes.join(", ")}`
1420
+ `Invalid file type: "${val.type}". Allowed types: ${options.allowedTypes.join(", ")}`,
1398
1421
  );
1399
1422
  }
1400
- if (typeof options?.maxSize !== "undefined" && val.size > options.maxSize) {
1423
+ if (
1424
+ typeof options?.maxSize !== "undefined" &&
1425
+ val.size > options.maxSize
1426
+ ) {
1401
1427
  throw new Error(
1402
- `File size exceeds the limit: ${val.size} bytes (Max: ${options.maxSize} bytes)`
1428
+ `File size exceeds the limit: ${val.size} bytes (Max: ${options.maxSize} bytes)`,
1403
1429
  );
1404
1430
  }
1405
1431
  if (typeof options?.maxFiles != "undefined" && options.maxFiles == 0) {
1406
1432
  throw new Error(
1407
- `Field "${key}" exceeds the maximum allowed file count of ${options.maxFiles}.`
1433
+ `Field "${key}" exceeds the maximum allowed file count of ${options.maxFiles}.`,
1408
1434
  );
1409
1435
  }
1410
1436
  val = new File([await val.arrayBuffer()], filename, {
1411
- type: val.type
1437
+ type: val.type,
1412
1438
  });
1413
1439
  }
1414
1440
  if (result[key]) {
1415
1441
  if (Array.isArray(result[key])) {
1416
- if (val instanceof File && typeof options?.maxFiles != "undefined" && result[key]?.length >= options.maxFiles) {
1442
+ if (
1443
+ val instanceof File &&
1444
+ typeof options?.maxFiles != "undefined" &&
1445
+ result[key]?.length >= options.maxFiles
1446
+ ) {
1417
1447
  throw new Error(
1418
- `Field "${key}" exceeds the maximum allowed file count of ${options.maxFiles}.`
1448
+ `Field "${key}" exceeds the maximum allowed file count of ${options.maxFiles}.`,
1419
1449
  );
1420
1450
  }
1421
1451
  result[key].push(val);
@@ -1455,7 +1485,7 @@ class Request {
1455
1485
  port: void 0,
1456
1486
  href: void 0,
1457
1487
  query: {},
1458
- pathname: "/"
1488
+ pathname: "/",
1459
1489
  };
1460
1490
  /** Query parameters extracted from the URL */
1461
1491
  query;
@@ -1662,7 +1692,7 @@ const httpStatusMap = {
1662
1692
  507: "Insufficient Storage",
1663
1693
  508: "Loop Detected",
1664
1694
  510: "Not Extended",
1665
- 511: "Network Authentication Required"
1695
+ 511: "Network Authentication Required",
1666
1696
  };
1667
1697
  class Context {
1668
1698
  #rawRequest;
@@ -1846,7 +1876,7 @@ class Context {
1846
1876
  const value = "";
1847
1877
  const cookieOptions = {
1848
1878
  ...options,
1849
- expires: /* @__PURE__ */ new Date(0)
1879
+ expires: /* @__PURE__ */ new Date(0),
1850
1880
  // Set expiration time to the past
1851
1881
  };
1852
1882
  const cookieHeader = `${name}=${value};${serializeOptions(cookieOptions)}`;
@@ -1861,13 +1891,13 @@ class Context {
1861
1891
  set: (name, value, options) => {
1862
1892
  const cookieHeader = `${name}=${value};${serializeOptions(options || {})}`;
1863
1893
  this.headers.set("Set-Cookie", cookieHeader);
1864
- }
1894
+ },
1865
1895
  };
1866
1896
  }
1867
1897
  json(body, ...args) {
1868
1898
  let status = this.#status;
1869
1899
  let headers = {
1870
- "Content-Type": "application/json; charset=utf-8"
1900
+ "Content-Type": "application/json; charset=utf-8",
1871
1901
  };
1872
1902
  if (typeof args[0] === "number") {
1873
1903
  status = args[0];
@@ -1879,7 +1909,7 @@ class Context {
1879
1909
  }
1880
1910
  return new Response(JSON.stringify(body), {
1881
1911
  status,
1882
- headers
1912
+ headers,
1883
1913
  });
1884
1914
  }
1885
1915
  send(body, ...args) {
@@ -1905,13 +1935,13 @@ class Context {
1905
1935
  }
1906
1936
  return new Response(body, {
1907
1937
  status,
1908
- headers
1938
+ headers,
1909
1939
  });
1910
1940
  }
1911
1941
  html(data, ...args) {
1912
1942
  let status = this.#status;
1913
1943
  let headers = {
1914
- "Content-Type": "text/html; charset=utf-8"
1944
+ "Content-Type": "text/html; charset=utf-8",
1915
1945
  };
1916
1946
  if (typeof args[0] === "number") {
1917
1947
  status = args[0];
@@ -1923,13 +1953,13 @@ class Context {
1923
1953
  }
1924
1954
  return new Response(data, {
1925
1955
  status,
1926
- headers
1956
+ headers,
1927
1957
  });
1928
1958
  }
1929
1959
  text(data, ...args) {
1930
1960
  let status = this.#status;
1931
1961
  let headers = {
1932
- "Content-Type": "text/plain; charset=utf-8"
1962
+ "Content-Type": "text/plain; charset=utf-8",
1933
1963
  };
1934
1964
  if (typeof args[0] === "number") {
1935
1965
  status = args[0];
@@ -1941,13 +1971,13 @@ class Context {
1941
1971
  }
1942
1972
  return new Response(data, {
1943
1973
  status,
1944
- headers
1974
+ headers,
1945
1975
  });
1946
1976
  }
1947
1977
  xml(data, ...args) {
1948
1978
  let status = this.#status;
1949
1979
  let headers = {
1950
- "Content-Type": "application/xml; charset=utf-8"
1980
+ "Content-Type": "application/xml; charset=utf-8",
1951
1981
  };
1952
1982
  if (typeof args[0] === "number") {
1953
1983
  status = args[0];
@@ -1959,7 +1989,7 @@ class Context {
1959
1989
  }
1960
1990
  return new Response(data, {
1961
1991
  status,
1962
- headers
1992
+ headers,
1963
1993
  });
1964
1994
  }
1965
1995
  /**
@@ -2045,10 +2075,7 @@ function serializeOptions(options) {
2045
2075
  return parts.join("; ");
2046
2076
  }
2047
2077
 
2048
- function useParams({
2049
- path,
2050
- urlPattern
2051
- }) {
2078
+ function useParams({ path, urlPattern }) {
2052
2079
  let params = {};
2053
2080
  path = path.replace(/^\/+|\/+$/g, "");
2054
2081
  urlPattern = urlPattern.replace(/^\/+|\/+$/g, "");
@@ -2064,11 +2091,16 @@ function useParams({
2064
2091
  const patternSegment = patternSegments[i];
2065
2092
  if (patternSegment?.startsWith("*")) {
2066
2093
  const trailingPatterns = patternSegments.slice(i + 1);
2067
- let paramName = patternSegment.length == 1 ? "*" : patternSegment?.slice(1);
2094
+ let paramName =
2095
+ patternSegment.length == 1 ? "*" : patternSegment?.slice(1);
2068
2096
  if (trailingPatterns.length > 0) {
2069
2097
  const expectedTrailing = trailingPatterns.join("/");
2070
- const actualTrailing = pathSegments.slice(pathLength - trailingPatterns.length).join("/");
2071
- const wildcardPath = pathSegments.slice(pathIndex, pathLength - trailingPatterns.length).join("/");
2098
+ const actualTrailing = pathSegments
2099
+ .slice(pathLength - trailingPatterns.length)
2100
+ .join("/");
2101
+ const wildcardPath = pathSegments
2102
+ .slice(pathIndex, pathLength - trailingPatterns.length)
2103
+ .join("/");
2072
2104
  if (expectedTrailing !== actualTrailing || !wildcardPath) {
2073
2105
  return { success: false, params: {} };
2074
2106
  }
@@ -2086,15 +2118,20 @@ function useParams({
2086
2118
  if (patternSegment.startsWith(":") && patternSegment.endsWith("?")) {
2087
2119
  const paramName = patternSegment.slice(1, -1);
2088
2120
  const nextPattern = patternSegments[i + 1];
2089
- if (nextPattern && !nextPattern.startsWith(":") && nextPattern !== "*" && pathIndex < pathLength && // !/test == /:user?/test
2090
- // বর্তমান পথ যদি পরবর্তী প্যাটার্ন মানে স্ট্যাটিক পথ এর সাথে মাইল তাহলে
2091
- pathSegments[pathIndex] === nextPattern) {
2121
+ if (
2122
+ nextPattern &&
2123
+ !nextPattern.startsWith(":") &&
2124
+ nextPattern !== "*" &&
2125
+ pathIndex < pathLength && // !/test == /:user?/test
2126
+ // বর্তমান পথ যদি পরবর্তী প্যাটার্ন মানে স্ট্যাটিক পথ এর সাথে মাইল তাহলে
2127
+ pathSegments[pathIndex] === nextPattern
2128
+ ) {
2092
2129
  params[paramName] = null;
2093
2130
  continue;
2094
2131
  }
2095
2132
  const remainingPatterns = patternSegments.slice(i + 1);
2096
2133
  const requiredCount = remainingPatterns.filter(
2097
- (seg) => !(seg.startsWith(":") && seg.endsWith("?"))
2134
+ (seg) => !(seg.startsWith(":") && seg.endsWith("?")),
2098
2135
  ).length;
2099
2136
  const remainingPath = pathLength - pathIndex;
2100
2137
  if (remainingPath === requiredCount) {
@@ -2138,7 +2175,7 @@ class TezX extends Router {
2138
2175
  env = {},
2139
2176
  logger = void 0,
2140
2177
  allowDuplicateMw = false,
2141
- overwriteMethod = true
2178
+ overwriteMethod = true,
2142
2179
  } = {}) {
2143
2180
  GlobalConfig.allowDuplicateMw = allowDuplicateMw;
2144
2181
  GlobalConfig.overwriteMethod = overwriteMethod;
@@ -2154,14 +2191,15 @@ class TezX extends Router {
2154
2191
  for (let pattern of this.routers.keys()) {
2155
2192
  const { success, params } = useParams({
2156
2193
  path: pathname,
2157
- urlPattern: pattern
2194
+ urlPattern: pattern,
2158
2195
  });
2159
- const handlers = routers.get(pattern)?.get(method) || routers.get(pattern)?.get("ALL");
2196
+ const handlers =
2197
+ routers.get(pattern)?.get(method) || routers.get(pattern)?.get("ALL");
2160
2198
  if (success && handlers) {
2161
2199
  return {
2162
2200
  callback: handlers.callback,
2163
2201
  middlewares: handlers.middlewares,
2164
- params
2202
+ params,
2165
2203
  };
2166
2204
  }
2167
2205
  }
@@ -2187,7 +2225,7 @@ class TezX extends Router {
2187
2225
  return {
2188
2226
  middlewares: handlers.middlewares,
2189
2227
  callback: handlers.callback,
2190
- params
2228
+ params,
2191
2229
  };
2192
2230
  }
2193
2231
  return null;
@@ -2195,11 +2233,12 @@ class TezX extends Router {
2195
2233
  return null;
2196
2234
  }
2197
2235
  findRoute(method, pathname) {
2198
- const route = this.#triRouter(method, pathname) || this.#hashRouter(method, pathname);
2236
+ const route =
2237
+ this.#triRouter(method, pathname) || this.#hashRouter(method, pathname);
2199
2238
  if (route) {
2200
2239
  return {
2201
2240
  ...route,
2202
- middlewares: [...route.middlewares]
2241
+ middlewares: [...route.middlewares],
2203
2242
  };
2204
2243
  }
2205
2244
  return null;
@@ -2257,12 +2296,13 @@ class TezX extends Router {
2257
2296
  let middlewares2 = find.middlewares;
2258
2297
  const response = await this.#createHandler(
2259
2298
  middlewares2,
2260
- callback
2299
+ callback,
2261
2300
  )(ctx2);
2262
2301
  if (response?.headers) {
2263
2302
  ctx2.headers.add(response.headers);
2264
2303
  }
2265
- const statusText = response?.statusText || httpStatusMap[response?.status] || "";
2304
+ const statusText =
2305
+ response?.statusText || httpStatusMap[response?.status] || "";
2266
2306
  const status = response.status || 200;
2267
2307
  let headers = ctx2.headers.toObject();
2268
2308
  if (logger.response) {
@@ -2272,13 +2312,13 @@ class TezX extends Router {
2272
2312
  return new Response(response.body, {
2273
2313
  status,
2274
2314
  statusText,
2275
- headers
2315
+ headers,
2276
2316
  });
2277
2317
  }
2278
2318
  return new Response(response.body, {
2279
2319
  status,
2280
2320
  statusText,
2281
- headers
2321
+ headers,
2282
2322
  });
2283
2323
  } else {
2284
2324
  if (logger.response) {
@@ -2286,7 +2326,7 @@ class TezX extends Router {
2286
2326
  }
2287
2327
  return GlobalConfig.notFound(ctx2);
2288
2328
  }
2289
- }
2329
+ },
2290
2330
  )(ctx);
2291
2331
  } catch (err) {
2292
2332
  let error = err;
@@ -2328,7 +2368,7 @@ function parseEnvFile(filePath, result) {
2328
2368
  fileContent = readFileSync(filePath, "utf8");
2329
2369
  } else if (runtime === "deno") {
2330
2370
  fileContent = new TextDecoder("utf-8").decode(
2331
- Deno.readFileSync(filePath)
2371
+ Deno.readFileSync(filePath),
2332
2372
  );
2333
2373
  }
2334
2374
  const lines = fileContent.split("\n");
@@ -2337,7 +2377,9 @@ function parseEnvFile(filePath, result) {
2337
2377
  if (!trimmedLine || trimmedLine.startsWith("#")) continue;
2338
2378
  const [key, value] = trimmedLine.split("=", 2).map((part) => part.trim());
2339
2379
  if (key && value) {
2340
- const parsedValue = value.replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
2380
+ const parsedValue = value
2381
+ .replace(/^"(.*)"$/, "$1")
2382
+ .replace(/^'(.*)'$/, "$1");
2341
2383
  result[key] = parsedValue;
2342
2384
  if (runtime === "node" || runtime === "bun") {
2343
2385
  process.env[key] = parsedValue;
@@ -2357,7 +2399,7 @@ function loadEnv(basePath = "./") {
2357
2399
  ".env.local",
2358
2400
  `.env.${process?.env?.NODE_ENV || "development"}`,
2359
2401
  // Supports NODE_ENV (e.g., .env.development, .env.production)
2360
- `.env.${process?.env?.NODE_ENV || "development"}.local`
2402
+ `.env.${process?.env?.NODE_ENV || "development"}.local`,
2361
2403
  ];
2362
2404
  for (const envFile of envFiles) {
2363
2405
  parseEnvFile(`${basePath}${envFile}`, result);
@@ -2376,15 +2418,16 @@ const COLORS = {
2376
2418
  magenta: "\x1B[35m",
2377
2419
  cyan: "\x1B[36m",
2378
2420
  bgBlue: "\x1B[44m",
2379
- bgMagenta: "\x1B[45m"};
2421
+ bgMagenta: "\x1B[45m",
2422
+ };
2380
2423
  const loggerOutput = (level, message, ...args) => {
2381
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
2424
+ const timestamp = /* @__PURE__ */ new Date().toISOString();
2382
2425
  const LEVEL_COLORS = {
2383
2426
  info: COLORS.blue,
2384
2427
  warn: COLORS.yellow,
2385
2428
  error: COLORS.red,
2386
2429
  debug: COLORS.cyan,
2387
- success: COLORS.green
2430
+ success: COLORS.green,
2388
2431
  };
2389
2432
  const prefix = `${COLORS.gray}[${timestamp}]${COLORS.reset}`;
2390
2433
  const levelText = `${LEVEL_COLORS[level]}[${level.toUpperCase()}]${COLORS.reset}`;
@@ -2396,37 +2439,30 @@ function logger() {
2396
2439
  return {
2397
2440
  request: (method, pathname) => {
2398
2441
  console.log(
2399
- `${COLORS.bold}<-- ${COLORS.reset}${COLORS.bgMagenta} ${method} ${COLORS.reset} ${pathname}`
2442
+ `${COLORS.bold}<-- ${COLORS.reset}${COLORS.bgMagenta} ${method} ${COLORS.reset} ${pathname}`,
2400
2443
  );
2401
2444
  },
2402
2445
  response: (method, pathname, status) => {
2403
2446
  const elapsed = performance.now() - startTime;
2404
2447
  console.log(
2405
- `${COLORS.bold}--> ${COLORS.reset}${COLORS.bgBlue} ${method} ${COLORS.reset} ${pathname} ${COLORS.yellow}${status}${COLORS.reset} ${COLORS.magenta}${elapsed.toFixed(2)}ms${COLORS.reset}`
2448
+ `${COLORS.bold}--> ${COLORS.reset}${COLORS.bgBlue} ${method} ${COLORS.reset} ${pathname} ${COLORS.yellow}${status}${COLORS.reset} ${COLORS.magenta}${elapsed.toFixed(2)}ms${COLORS.reset}`,
2406
2449
  );
2407
2450
  },
2408
2451
  info: (msg, ...args) => loggerOutput("info", msg, ...args),
2409
2452
  warn: (msg, ...args) => loggerOutput("warn", msg, ...args),
2410
2453
  error: (msg, ...args) => loggerOutput("error", msg, ...args),
2411
2454
  debug: (msg, ...args) => loggerOutput("debug", msg, ...args),
2412
- success: (msg, ...args) => loggerOutput("success", msg, ...args)
2455
+ success: (msg, ...args) => loggerOutput("success", msg, ...args),
2413
2456
  };
2414
2457
  }
2415
2458
  return {
2416
- request: (method, pathname) => {
2417
- },
2418
- response: (method, pathname, status) => {
2419
- },
2420
- info: (msg, ...args) => {
2421
- },
2422
- warn: (msg, ...args) => {
2423
- },
2424
- error: (msg, ...args) => {
2425
- },
2426
- debug: (msg, ...args) => {
2427
- },
2428
- success: (msg, ...args) => {
2429
- }
2459
+ request: (method, pathname) => {},
2460
+ response: (method, pathname, status) => {},
2461
+ info: (msg, ...args) => {},
2462
+ warn: (msg, ...args) => {},
2463
+ error: (msg, ...args) => {},
2464
+ debug: (msg, ...args) => {},
2465
+ success: (msg, ...args) => {},
2430
2466
  };
2431
2467
  }
2432
2468
 
@@ -2437,7 +2473,7 @@ function cors(option = {}) {
2437
2473
  credentials,
2438
2474
  exposedHeaders,
2439
2475
  maxAge,
2440
- origin
2476
+ origin,
2441
2477
  } = option;
2442
2478
  return async (ctx, next) => {
2443
2479
  const reqOrigin = ctx.req.headers.get("origin") || "";
@@ -2461,16 +2497,16 @@ function cors(option = {}) {
2461
2497
  ctx.headers.set("Access-Control-Allow-Origin", allowOrigin);
2462
2498
  ctx.headers.set(
2463
2499
  "Access-Control-Allow-Methods",
2464
- (methods || ["GET", "POST", "PUT", "DELETE"]).join(", ")
2500
+ (methods || ["GET", "POST", "PUT", "DELETE"]).join(", "),
2465
2501
  );
2466
2502
  ctx.headers.set(
2467
2503
  "Access-Control-Allow-Headers",
2468
- (allowedHeaders || ["Content-Type", "Authorization"]).join(", ")
2504
+ (allowedHeaders || ["Content-Type", "Authorization"]).join(", "),
2469
2505
  );
2470
2506
  if (exposedHeaders) {
2471
2507
  ctx.headers.set(
2472
2508
  "Access-Control-Expose-Headers",
2473
- exposedHeaders.join(", ")
2509
+ exposedHeaders.join(", "),
2474
2510
  );
2475
2511
  }
2476
2512
  if (credentials) {
@@ -2482,11 +2518,22 @@ function cors(option = {}) {
2482
2518
  if (ctx.req.method === "OPTIONS") {
2483
2519
  return new Response(null, {
2484
2520
  status: 204,
2485
- headers: ctx.headers.toObject()
2521
+ headers: ctx.headers.toObject(),
2486
2522
  });
2487
2523
  }
2488
2524
  return await next();
2489
2525
  };
2490
2526
  }
2491
2527
 
2492
- export { Router, TezResponse, TezX, bunAdapter, cors, denoAdapter, loadEnv, logger, nodeAdapter, useParams };
2528
+ export {
2529
+ Router,
2530
+ TezResponse,
2531
+ TezX,
2532
+ bunAdapter,
2533
+ cors,
2534
+ denoAdapter,
2535
+ loadEnv,
2536
+ logger,
2537
+ nodeAdapter,
2538
+ useParams,
2539
+ };