@arkyn/server 2.0.1-beta.8 → 2.0.1

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 (244) hide show
  1. package/LICENSE.txt +24 -0
  2. package/README.md +116 -0
  3. package/dist/api/__test__/deleteRequest.spec.d.ts +2 -0
  4. package/dist/api/__test__/deleteRequest.spec.d.ts.map +1 -0
  5. package/dist/api/__test__/deleteRequest.spec.js +84 -0
  6. package/dist/api/__test__/getRequest.spec.d.ts +2 -0
  7. package/dist/api/__test__/getRequest.spec.d.ts.map +1 -0
  8. package/dist/api/__test__/getRequest.spec.js +62 -0
  9. package/dist/api/__test__/inboxFlowRequest.spec.d.ts +2 -0
  10. package/dist/api/__test__/inboxFlowRequest.spec.d.ts.map +1 -0
  11. package/dist/api/__test__/inboxFlowRequest.spec.js +96 -0
  12. package/dist/api/__test__/makeRequest.spec.d.ts +2 -0
  13. package/dist/api/__test__/makeRequest.spec.d.ts.map +1 -0
  14. package/dist/api/__test__/makeRequest.spec.js +80 -0
  15. package/dist/api/__test__/patchRequest.spec.d.ts +2 -0
  16. package/dist/api/__test__/patchRequest.spec.d.ts.map +1 -0
  17. package/dist/api/__test__/patchRequest.spec.js +84 -0
  18. package/dist/api/__test__/postRequest.spec.d.ts +2 -0
  19. package/dist/api/__test__/postRequest.spec.d.ts.map +1 -0
  20. package/dist/api/__test__/postRequest.spec.js +84 -0
  21. package/dist/api/__test__/putRequest.spec.d.ts +2 -0
  22. package/dist/api/__test__/putRequest.spec.d.ts.map +1 -0
  23. package/dist/api/__test__/putRequest.spec.js +84 -0
  24. package/dist/api/deleteRequest.d.ts +13 -0
  25. package/dist/api/deleteRequest.d.ts.map +1 -0
  26. package/dist/api/deleteRequest.js +14 -0
  27. package/dist/api/getRequest.d.ts +12 -0
  28. package/dist/api/getRequest.d.ts.map +1 -0
  29. package/dist/api/getRequest.js +13 -0
  30. package/dist/api/inboxFlowRequest.d.ts +40 -0
  31. package/dist/api/inboxFlowRequest.d.ts.map +1 -0
  32. package/dist/api/inboxFlowRequest.js +63 -0
  33. package/dist/api/makeRequest.d.ts +38 -0
  34. package/dist/api/makeRequest.d.ts.map +1 -0
  35. package/dist/api/makeRequest.js +103 -0
  36. package/dist/api/patchRequest.d.ts +13 -0
  37. package/dist/api/patchRequest.d.ts.map +1 -0
  38. package/dist/api/patchRequest.js +14 -0
  39. package/dist/api/postRequest.d.ts +13 -0
  40. package/dist/api/postRequest.d.ts.map +1 -0
  41. package/dist/api/postRequest.js +14 -0
  42. package/dist/api/putRequest.d.ts +13 -0
  43. package/dist/api/putRequest.d.ts.map +1 -0
  44. package/dist/api/putRequest.js +14 -0
  45. package/dist/config/__test__/apiInstance.spec.d.ts +2 -0
  46. package/dist/config/__test__/apiInstance.spec.d.ts.map +1 -0
  47. package/dist/config/__test__/apiInstance.spec.js +86 -0
  48. package/dist/config/__test__/inboxFlowInstance.spec.d.ts +2 -0
  49. package/dist/config/__test__/inboxFlowInstance.spec.d.ts.map +1 -0
  50. package/dist/config/__test__/inboxFlowInstance.spec.js +48 -0
  51. package/dist/config/apiInstance.d.ts +80 -0
  52. package/dist/config/apiInstance.d.ts.map +1 -0
  53. package/dist/config/apiInstance.js +111 -0
  54. package/dist/config/inboxFlowInstance.d.ts +44 -0
  55. package/dist/config/inboxFlowInstance.d.ts.map +1 -0
  56. package/dist/config/inboxFlowInstance.js +46 -0
  57. package/dist/http/badResponses/__test__/badGateway.spec.d.ts +2 -0
  58. package/dist/http/badResponses/__test__/badGateway.spec.d.ts.map +1 -0
  59. package/dist/http/badResponses/__test__/badGateway.spec.js +42 -0
  60. package/dist/http/badResponses/__test__/badRequest.spec.d.ts +2 -0
  61. package/dist/http/badResponses/__test__/badRequest.spec.d.ts.map +1 -0
  62. package/dist/http/badResponses/__test__/badRequest.spec.js +40 -0
  63. package/dist/http/badResponses/__test__/conflict.spec.d.ts +2 -0
  64. package/dist/http/badResponses/__test__/conflict.spec.d.ts.map +1 -0
  65. package/dist/http/badResponses/__test__/conflict.spec.js +40 -0
  66. package/dist/http/badResponses/__test__/forbidden.spec.d.ts +2 -0
  67. package/dist/http/badResponses/__test__/forbidden.spec.d.ts.map +1 -0
  68. package/dist/http/badResponses/__test__/forbidden.spec.js +40 -0
  69. package/dist/http/badResponses/__test__/notFound.spec.d.ts +2 -0
  70. package/dist/http/badResponses/__test__/notFound.spec.d.ts.map +1 -0
  71. package/dist/http/badResponses/__test__/notFound.spec.js +40 -0
  72. package/dist/http/badResponses/__test__/notImplemented.spec.d.ts +2 -0
  73. package/dist/http/badResponses/__test__/notImplemented.spec.d.ts.map +1 -0
  74. package/dist/http/badResponses/__test__/notImplemented.spec.js +40 -0
  75. package/dist/http/badResponses/__test__/serverError.spec.d.ts +2 -0
  76. package/dist/http/badResponses/__test__/serverError.spec.d.ts.map +1 -0
  77. package/dist/http/badResponses/__test__/serverError.spec.js +40 -0
  78. package/dist/http/badResponses/__test__/unauthorized.spec.d.ts +2 -0
  79. package/dist/http/badResponses/__test__/unauthorized.spec.d.ts.map +1 -0
  80. package/dist/http/badResponses/__test__/unauthorized.spec.js +40 -0
  81. package/dist/http/badResponses/__test__/unprocessableEntity.spec.d.ts +2 -0
  82. package/dist/http/badResponses/__test__/unprocessableEntity.spec.d.ts.map +1 -0
  83. package/dist/http/badResponses/__test__/unprocessableEntity.spec.js +66 -0
  84. package/dist/http/badResponses/badGateway.d.ts +23 -0
  85. package/dist/http/badResponses/badGateway.d.ts.map +1 -1
  86. package/dist/http/badResponses/badGateway.js +24 -1
  87. package/dist/http/badResponses/badRequest.d.ts +23 -0
  88. package/dist/http/badResponses/badRequest.d.ts.map +1 -1
  89. package/dist/http/badResponses/badRequest.js +24 -1
  90. package/dist/http/badResponses/conflict.d.ts +23 -0
  91. package/dist/http/badResponses/conflict.d.ts.map +1 -1
  92. package/dist/http/badResponses/conflict.js +24 -1
  93. package/dist/http/badResponses/forbidden.d.ts +23 -0
  94. package/dist/http/badResponses/forbidden.d.ts.map +1 -1
  95. package/dist/http/badResponses/forbidden.js +25 -2
  96. package/dist/http/badResponses/notFound.d.ts +23 -0
  97. package/dist/http/badResponses/notFound.d.ts.map +1 -1
  98. package/dist/http/badResponses/notFound.js +24 -1
  99. package/dist/http/badResponses/notImplemented.d.ts +23 -0
  100. package/dist/http/badResponses/notImplemented.d.ts.map +1 -1
  101. package/dist/http/badResponses/notImplemented.js +24 -1
  102. package/dist/http/badResponses/serverError.d.ts +23 -0
  103. package/dist/http/badResponses/serverError.d.ts.map +1 -1
  104. package/dist/http/badResponses/serverError.js +24 -1
  105. package/dist/http/badResponses/unauthorized.d.ts +23 -0
  106. package/dist/http/badResponses/unauthorized.d.ts.map +1 -1
  107. package/dist/http/badResponses/unauthorized.js +24 -1
  108. package/dist/http/badResponses/unprocessableEntity.d.ts +28 -1
  109. package/dist/http/badResponses/unprocessableEntity.d.ts.map +1 -1
  110. package/dist/http/badResponses/unprocessableEntity.js +30 -3
  111. package/dist/http/successResponses/__test__/created.spec.d.ts +2 -0
  112. package/dist/http/successResponses/__test__/created.spec.d.ts.map +1 -0
  113. package/dist/http/successResponses/__test__/created.spec.js +57 -0
  114. package/dist/http/successResponses/__test__/found.spec.d.ts +2 -0
  115. package/dist/http/successResponses/__test__/found.spec.d.ts.map +1 -0
  116. package/dist/http/successResponses/__test__/found.spec.js +57 -0
  117. package/dist/http/successResponses/__test__/noContent.spec.d.ts +2 -0
  118. package/dist/http/successResponses/__test__/noContent.spec.d.ts.map +1 -0
  119. package/dist/http/successResponses/__test__/noContent.spec.js +40 -0
  120. package/dist/http/successResponses/__test__/success.spec.d.ts +2 -0
  121. package/dist/http/successResponses/__test__/success.spec.d.ts.map +1 -0
  122. package/dist/http/successResponses/__test__/success.spec.js +60 -0
  123. package/dist/http/successResponses/__test__/updated.spec.d.ts +2 -0
  124. package/dist/http/successResponses/__test__/updated.spec.d.ts.map +1 -0
  125. package/dist/http/successResponses/__test__/updated.spec.js +60 -0
  126. package/dist/http/successResponses/created.d.ts +25 -0
  127. package/dist/http/successResponses/created.d.ts.map +1 -1
  128. package/dist/http/successResponses/created.js +25 -0
  129. package/dist/http/successResponses/found.d.ts +28 -0
  130. package/dist/http/successResponses/found.d.ts.map +1 -1
  131. package/dist/http/successResponses/found.js +28 -0
  132. package/dist/http/successResponses/noContent.d.ts +16 -1
  133. package/dist/http/successResponses/noContent.d.ts.map +1 -1
  134. package/dist/http/successResponses/noContent.js +16 -8
  135. package/dist/http/successResponses/success.d.ts +25 -0
  136. package/dist/http/successResponses/success.d.ts.map +1 -1
  137. package/dist/http/successResponses/success.js +25 -0
  138. package/dist/http/successResponses/updated.d.ts +25 -0
  139. package/dist/http/successResponses/updated.d.ts.map +1 -1
  140. package/dist/http/successResponses/updated.js +25 -0
  141. package/dist/index.d.ts +6 -0
  142. package/dist/index.d.ts.map +1 -1
  143. package/dist/index.js +10 -0
  144. package/dist/services/__test__/decodeRequestBody.spec.d.ts +2 -0
  145. package/dist/services/__test__/decodeRequestBody.spec.d.ts.map +1 -0
  146. package/dist/services/__test__/decodeRequestBody.spec.js +39 -0
  147. package/dist/services/__test__/errorHandler.spec.d.ts +2 -0
  148. package/dist/services/__test__/errorHandler.spec.d.ts.map +1 -0
  149. package/dist/services/__test__/errorHandler.spec.js +115 -0
  150. package/dist/services/__test__/formParse.spec.d.ts +2 -0
  151. package/dist/services/__test__/formParse.spec.d.ts.map +1 -0
  152. package/dist/services/__test__/formParse.spec.js +78 -0
  153. package/dist/services/__test__/getCaller.spec.d.ts +2 -0
  154. package/dist/services/__test__/getCaller.spec.d.ts.map +1 -0
  155. package/dist/services/__test__/getCaller.spec.js +60 -0
  156. package/dist/services/__test__/getScopedParams.spec.d.ts +2 -0
  157. package/dist/services/__test__/getScopedParams.spec.d.ts.map +1 -0
  158. package/dist/services/__test__/getScopedParams.spec.js +51 -0
  159. package/dist/services/__test__/schemaValidator.spec.d.ts +2 -0
  160. package/dist/services/__test__/schemaValidator.spec.d.ts.map +1 -0
  161. package/dist/services/__test__/schemaValidator.spec.js +89 -0
  162. package/dist/services/decodeErrorMessageFromRequest.d.ts +17 -0
  163. package/dist/services/decodeErrorMessageFromRequest.d.ts.map +1 -0
  164. package/dist/services/decodeErrorMessageFromRequest.js +30 -0
  165. package/dist/services/decodeRequestBody.d.ts.map +1 -1
  166. package/dist/services/decodeRequestBody.js +12 -16
  167. package/dist/services/errorHandler.d.ts +42 -1
  168. package/dist/services/errorHandler.d.ts.map +1 -1
  169. package/dist/services/errorHandler.js +42 -0
  170. package/dist/services/formParse.d.ts.map +1 -1
  171. package/dist/services/formParse.js +4 -2
  172. package/dist/services/getCaller.d.ts +17 -0
  173. package/dist/services/getCaller.d.ts.map +1 -0
  174. package/dist/services/getCaller.js +45 -0
  175. package/dist/services/httpDebug.d.ts +35 -0
  176. package/dist/services/httpDebug.d.ts.map +1 -0
  177. package/dist/services/httpDebug.js +56 -0
  178. package/dist/services/schemaValidator.d.ts +13 -0
  179. package/dist/services/schemaValidator.d.ts.map +1 -0
  180. package/dist/services/schemaValidator.js +51 -0
  181. package/package.json +13 -6
  182. package/src/api/__test__/deleteRequest.spec.ts +107 -0
  183. package/src/api/__test__/getRequest.spec.ts +76 -0
  184. package/src/api/__test__/inboxFlowRequest.spec.ts +125 -0
  185. package/src/api/__test__/makeRequest.spec.ts +121 -0
  186. package/src/api/__test__/patchRequest.spec.ts +125 -0
  187. package/src/api/__test__/postRequest.spec.ts +125 -0
  188. package/src/api/__test__/putRequest.spec.ts +125 -0
  189. package/src/api/deleteRequest.ts +22 -0
  190. package/src/api/getRequest.ts +20 -0
  191. package/src/api/inboxFlowRequest.ts +76 -0
  192. package/src/api/makeRequest.ts +117 -0
  193. package/src/api/patchRequest.ts +22 -0
  194. package/src/api/postRequest.ts +22 -0
  195. package/src/api/putRequest.ts +22 -0
  196. package/src/config/__test__/apiInstance.spec.ts +129 -0
  197. package/src/config/__test__/inboxFlowInstance.spec.ts +61 -0
  198. package/src/config/apiInstance.ts +148 -0
  199. package/src/config/inboxFlowInstance.ts +65 -0
  200. package/src/http/badResponses/__test__/badGateway.spec.ts +50 -0
  201. package/src/http/badResponses/__test__/badRequest.spec.ts +50 -0
  202. package/src/http/badResponses/__test__/conflict.spec.ts +50 -0
  203. package/src/http/badResponses/__test__/forbidden.spec.ts +50 -0
  204. package/src/http/badResponses/__test__/notFound.spec.ts +50 -0
  205. package/src/http/badResponses/__test__/notImplemented.spec.ts +50 -0
  206. package/src/http/badResponses/__test__/serverError.spec.ts +50 -0
  207. package/src/http/badResponses/__test__/unauthorized.spec.ts +50 -0
  208. package/src/http/badResponses/__test__/unprocessableEntity.spec.ts +76 -0
  209. package/src/http/badResponses/badGateway.ts +29 -2
  210. package/src/http/badResponses/badRequest.ts +29 -2
  211. package/src/http/badResponses/conflict.ts +29 -2
  212. package/src/http/badResponses/forbidden.ts +30 -3
  213. package/src/http/badResponses/notFound.ts +29 -2
  214. package/src/http/badResponses/notImplemented.ts +29 -2
  215. package/src/http/badResponses/serverError.ts +29 -2
  216. package/src/http/badResponses/unauthorized.ts +29 -2
  217. package/src/http/badResponses/unprocessableEntity.ts +33 -2
  218. package/src/http/successResponses/__test__/created.spec.ts +65 -0
  219. package/src/http/successResponses/__test__/found.spec.ts +65 -0
  220. package/src/http/successResponses/__test__/noContent.spec.ts +49 -0
  221. package/src/http/successResponses/__test__/success.spec.ts +68 -0
  222. package/src/http/successResponses/__test__/updated.spec.ts +68 -0
  223. package/src/http/successResponses/created.ts +31 -2
  224. package/src/http/successResponses/found.ts +32 -0
  225. package/src/http/successResponses/noContent.ts +20 -11
  226. package/src/http/successResponses/success.ts +31 -2
  227. package/src/http/successResponses/updated.ts +31 -2
  228. package/src/index.ts +9 -1
  229. package/src/services/__test__/decodeRequestBody.spec.ts +51 -0
  230. package/src/services/__test__/errorHandler.spec.ts +133 -0
  231. package/src/services/__test__/formParse.spec.ts +96 -0
  232. package/src/services/__test__/getCaller.spec.ts +78 -0
  233. package/src/services/__test__/getScopedParams.spec.ts +68 -0
  234. package/src/services/__test__/schemaValidator.spec.ts +106 -0
  235. package/src/services/decodeErrorMessageFromRequest.ts +36 -0
  236. package/src/services/decodeRequestBody.ts +11 -15
  237. package/src/services/errorHandler.ts +45 -1
  238. package/src/services/formParse.ts +4 -5
  239. package/src/services/getCaller.ts +39 -21
  240. package/src/services/httpDebug.ts +46 -5
  241. package/vitest.config.ts +5 -0
  242. package/dist/http/httpDebug.d.ts +0 -3
  243. package/dist/http/httpDebug.d.ts.map +0 -1
  244. package/dist/http/httpDebug.js +0 -15
@@ -0,0 +1,106 @@
1
+ import { z } from "zod";
2
+ import { SchemaValidator } from "../schemaValidator";
3
+ import { httpDebug } from "../httpDebug";
4
+ import { ServerError } from "../../http/badResponses/serverError";
5
+ import { UnprocessableEntity } from "../../http/badResponses/unprocessableEntity";
6
+ import { describe, expect, it, vi } from "vitest";
7
+
8
+ vi.mock("../getCaller", () => ({
9
+ getCaller: vi.fn(() => ({
10
+ callerInfo: "mockedCallerInfo",
11
+ functionName: "mockedFunctionName",
12
+ })),
13
+ }));
14
+
15
+ vi.mock("../httpDebug", () => ({
16
+ httpDebug: vi.fn(),
17
+ }));
18
+
19
+ describe("SchemaValidator", () => {
20
+ const schema = z.object({
21
+ name: z.string().min(1, "Name is required"),
22
+ age: z.number().min(18, "Must be at least 18"),
23
+ });
24
+
25
+ const validator = new SchemaValidator(schema);
26
+
27
+ describe("constructor", () => {
28
+ it("should initialize with caller info and function name", () => {
29
+ expect(validator.callerInfo).toBe("mockedCallerInfo");
30
+ expect(validator.functionName).toBe("mockedFunctionName");
31
+ });
32
+ });
33
+
34
+ describe("isValid", () => {
35
+ it("should return true for valid data", () => {
36
+ const data = { name: "John", age: 25 };
37
+ expect(validator.isValid(data)).toBe(true);
38
+ });
39
+
40
+ it("should return false for invalid data", () => {
41
+ const data = { name: "", age: 17 };
42
+ expect(validator.isValid(data)).toBe(false);
43
+ });
44
+ });
45
+
46
+ describe("safeValidate", () => {
47
+ it("should return success for valid data", () => {
48
+ const data = { name: "John", age: 25 };
49
+ const result = validator.safeValidate(data);
50
+ expect(result.success).toBe(true);
51
+ expect(result.data).toEqual(data);
52
+ });
53
+
54
+ it("should return failure for invalid data", () => {
55
+ const data = { name: "", age: 17 };
56
+ const result = validator.safeValidate(data);
57
+ expect(result.success).toBe(false);
58
+ if (!result.success) expect(result.error.issues).toHaveLength(2);
59
+ });
60
+ });
61
+
62
+ describe("validate", () => {
63
+ it("should return parsed data for valid input", () => {
64
+ const data = { name: "John", age: 25 };
65
+ expect(validator.validate(data)).toEqual(data);
66
+ });
67
+
68
+ it("should throw ServerError for invalid input", () => {
69
+ const data = { name: "", age: 17 };
70
+ expect(() => validator.validate(data)).toThrow(ServerError);
71
+ });
72
+ });
73
+
74
+ describe("formValidate", () => {
75
+ it("should return parsed data for valid input", () => {
76
+ const data = { name: "John", age: 25 };
77
+ expect(validator.formValidate(data)).toEqual(data);
78
+ });
79
+
80
+ it("should throw UnprocessableEntity for invalid input", () => {
81
+ const data = { name: "", age: 17 };
82
+ expect(() => validator.formValidate(data)).toThrow(UnprocessableEntity);
83
+ });
84
+
85
+ it("should call httpDebug with formParsed data on validation failure", () => {
86
+ const data = { name: "", age: 17 };
87
+
88
+ try {
89
+ validator.formValidate(data);
90
+ } catch (error) {
91
+ // Ignore the error
92
+ }
93
+
94
+ expect(httpDebug).toHaveBeenCalledWith(
95
+ "UnprocessableEntity",
96
+ expect.objectContaining({
97
+ success: false,
98
+ fieldErrors: {
99
+ name: "Name is required",
100
+ age: "Must be at least 18",
101
+ },
102
+ })
103
+ );
104
+ });
105
+ });
106
+ });
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Decodes an error message from a given request data object or response object.
3
+ *
4
+ * This function attempts to extract a meaningful error message from the provided
5
+ * `data` or `response` objects by checking various properties in a specific order.
6
+ * If no valid error message is found, it returns a default message: "Missing error message".
7
+ *
8
+ * @param data - The data object that may contain error information. It can have properties
9
+ * such as `message`, `error`, or `error.message` that are checked for a string value.
10
+ * @param response - The response object that may contain a `statusText` property
11
+ * representing the HTTP status text.
12
+ * @returns A string representing the decoded error message, or a default message
13
+ * if no error message is found.
14
+ */
15
+
16
+ function decodeErrorMessageFromRequest(data: any, response: Response): string {
17
+ if (data?.message && typeof data?.message === "string") {
18
+ return data?.message;
19
+ }
20
+
21
+ if (data?.error && typeof data?.error === "string") {
22
+ return data?.error;
23
+ }
24
+
25
+ if (data?.error?.message && typeof data?.error?.message === "string") {
26
+ return data?.error?.message;
27
+ }
28
+
29
+ if (response?.statusText && typeof response?.statusText === "string") {
30
+ return response?.statusText;
31
+ }
32
+
33
+ return "Missing error message";
34
+ }
35
+
36
+ export { decodeErrorMessageFromRequest };
@@ -1,4 +1,5 @@
1
1
  import type { DecodeRequestBodyFunction } from "@arkyn/types";
2
+ import { BadRequest } from "../http/badResponses/badRequest";
2
3
 
3
4
  /**
4
5
  * Decodes the body of an incoming request into a JavaScript object.
@@ -17,27 +18,22 @@ import type { DecodeRequestBodyFunction } from "@arkyn/types";
17
18
  const decodeRequestBody: DecodeRequestBodyFunction = async (req) => {
18
19
  let data: any;
19
20
 
20
- try {
21
- const arrayBuffer = await req.arrayBuffer();
22
- const text = new TextDecoder().decode(arrayBuffer);
21
+ const arrayBuffer = await req.arrayBuffer();
22
+ const text = new TextDecoder().decode(arrayBuffer);
23
23
 
24
+ try {
25
+ data = JSON.parse(text);
26
+ } catch (jsonError) {
24
27
  try {
25
- data = JSON.parse(text);
26
- } catch (jsonError) {
27
- try {
28
+ if (text.includes("=")) {
28
29
  const formData = new URLSearchParams(text);
29
30
  data = Object.fromEntries(formData.entries());
30
- } catch (formDataError) {
31
- console.error("Failed to extract data from request:", {
32
- jsonError,
33
- formDataError,
34
- });
35
- data = {};
31
+ } else {
32
+ throw new BadRequest("Invalid URLSearchParams format");
36
33
  }
34
+ } catch (formDataError) {
35
+ throw new BadRequest("Failed to extract data from request");
37
36
  }
38
- } catch (error) {
39
- console.error("Failed to read request body:", error);
40
- data = {};
41
37
  }
42
38
 
43
39
  return data;
@@ -14,7 +14,49 @@ import { NoContent } from "../http/successResponses/noContent";
14
14
  import { Success } from "../http/successResponses/success";
15
15
  import { Updated } from "../http/successResponses/updated";
16
16
 
17
- function errorHandler(error: any) {
17
+ /**
18
+ * Handles errors and converts them into appropriate HTTP responses.
19
+ *
20
+ * This function takes an error object and determines its type to return
21
+ * the corresponding HTTP response. It supports both success and error
22
+ * response types, converting them into a standardized format using the
23
+ * `toResponse` method when applicable.
24
+ *
25
+ * @param error - The error object to handle. It can be an instance of various
26
+ * HTTP response classes or a generic error.
27
+ *
28
+ * @returns The corresponding HTTP response object if the error matches a known
29
+ * type, or `undefined` if no match is found.
30
+ *
31
+ * ### Supported Success Responses:
32
+ * - `Found`
33
+ * - `Created`
34
+ * - `Updated`
35
+ * - `Success`
36
+ * - `NoContent`
37
+ *
38
+ * ### Supported Error Responses:
39
+ * - `BadGateway`
40
+ * - `BadRequest`
41
+ * - `Conflict`
42
+ * - `Forbidden`
43
+ * - `NotFound`
44
+ * - `NotImplemented`
45
+ * - `ServerError`
46
+ * - `Unauthorized`
47
+ * - `UnprocessableEntity`
48
+ *
49
+ * ### Example Usage:
50
+ * ```typescript
51
+ * try {
52
+ * // Some operation that might throw an error
53
+ * } catch (error) {
54
+ * return errorHandler(error);
55
+ * }
56
+ * ```
57
+ */
58
+
59
+ function errorHandler(error: any): Response {
18
60
  switch (true) {
19
61
  case error instanceof Response:
20
62
  return error;
@@ -50,6 +92,8 @@ function errorHandler(error: any) {
50
92
  case error instanceof UnprocessableEntity:
51
93
  return error.toResponse();
52
94
  }
95
+
96
+ return new ServerError("Server error").toResponse();
53
97
  }
54
98
 
55
99
  export { errorHandler };
@@ -46,12 +46,11 @@ function formParse<T extends FormParseProps>([
46
46
  const zodResponse = schema.safeParse(formData);
47
47
 
48
48
  if (zodResponse.success === false) {
49
- const errorsArray = Object.entries(
50
- zodResponse.error.formErrors.fieldErrors
51
- );
52
-
53
49
  const errorsObject = Object.fromEntries(
54
- errorsArray.map((item) => [item[0], item[1]?.[0] || "Error"])
50
+ zodResponse.error.errors.map((item) => [
51
+ item.path.join("."),
52
+ item.message,
53
+ ])
55
54
  );
56
55
 
57
56
  return {
@@ -1,36 +1,54 @@
1
1
  import path from "path";
2
2
 
3
+ /**
4
+ * Retrieves information about the caller of the current function.
5
+ *
6
+ * This function analyzes the stack trace to determine the file path and function name
7
+ * of the caller. It excludes stack trace entries related to the `@arkyn/server` package
8
+ * and attempts to resolve the file path relative to the project root directory.
9
+ *
10
+ * @returns An object containing:
11
+ * - `functionName`: The name of the function that called the current function, or "Unknown function" if it cannot be determined.
12
+ * - `callerInfo`: The file path of the caller relative to the project root, or "Unknown caller" if it cannot be determined.
13
+ */
14
+
3
15
  function getCaller() {
4
- // Diretório raiz do projeto
5
16
  const projectRoot = process.cwd();
6
17
 
7
- // Captura a stack trace
8
18
  const error = new Error();
9
19
  const stackLines = error.stack?.split("\n").map((line) => line.trim()) || [];
10
20
 
11
21
  let callerInfo = "Unknown caller";
12
22
  let functionName = "Unknown function";
13
23
 
14
- for (const line of stackLines) {
15
- if (
16
- !line.includes("httpDebug") &&
17
- !line.includes("BadGateway") &&
18
- !line.includes("BadRequest")
19
- ) {
20
- // Captura formatos diferentes de stack trace
21
- const match = line.match(/at (.+?) \((.+?)\)/) || line.match(/at (.+)/);
22
- if (match) {
23
- functionName = match[1].split(" ")[0]; // Nome da função
24
- let fullPath = match[2] || match[1]; // Caminho absoluto do arquivo
25
-
26
- // Transforma caminho absoluto em relativo ao projeto
27
- if (fullPath.startsWith(projectRoot)) {
28
- fullPath = path.relative(projectRoot, fullPath);
29
- }
30
-
31
- callerInfo = fullPath;
32
- break;
24
+ const relevantLines = stackLines.filter(
25
+ (line) => !line.includes("@arkyn/server")
26
+ );
27
+
28
+ let foundGetCaller = false;
29
+ for (const line of relevantLines) {
30
+ if (!foundGetCaller) {
31
+ if (line.includes("getCaller")) {
32
+ foundGetCaller = true;
33
+ }
34
+ continue;
35
+ }
36
+
37
+ const match = line.match(/at (.+?) \((.+?)\)/) || line.match(/at (.+)/);
38
+ if (match) {
39
+ const rawFuncName = match[1]?.split(" ")[0] || "";
40
+
41
+ functionName =
42
+ rawFuncName && !rawFuncName.includes("/")
43
+ ? rawFuncName
44
+ : "Unknown function";
45
+
46
+ let fullPath = match[2] || match[1];
47
+ if (fullPath.startsWith(projectRoot)) {
48
+ fullPath = path.relative(projectRoot, fullPath);
33
49
  }
50
+ callerInfo = fullPath;
51
+ break;
34
52
  }
35
53
  }
36
54
 
@@ -1,5 +1,39 @@
1
+ import { InboxFlowInstance } from "../config/inboxFlowInstance";
1
2
  import { getCaller } from "../services/getCaller";
2
3
 
4
+ /**
5
+ * Logs debug information to the console when in development mode or when the
6
+ * `SHOW_ERRORS_IN_CONSOLE` environment variable is set to "true".
7
+ *
8
+ * This function provides detailed information about the caller function,
9
+ * its location, and the provided body and cause, if any.
10
+ *
11
+ * @param name - A string representing the name or context of the debug log.
12
+ * @param body - The main content or data to be logged.
13
+ * @param cause - (Optional) Additional information or error cause to be logged.
14
+ *
15
+ * @remarks
16
+ * The debug logs are only displayed when the application is running in
17
+ * development mode (`NODE_ENV === "development"`) or when the
18
+ * `SHOW_ERRORS_IN_CONSOLE` environment variable is explicitly set to "true".
19
+ *
20
+ * The logs include:
21
+ * - The name of the debug context.
22
+ * - The caller function name and its location.
23
+ * - The provided body content.
24
+ * - The optional cause, if provided.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * httpDebug("FetchUserData", { userId: 123 });
29
+ * ```
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * httpDebug("FetchUserDataError", { userId: 123 }, new Error("User not found"));
34
+ * ```
35
+ */
36
+
3
37
  function httpDebug(name: string, body: any, cause?: any) {
4
38
  const isDebugMode =
5
39
  process.env.NODE_ENV === "development" ||
@@ -12,11 +46,18 @@ function httpDebug(name: string, body: any, cause?: any) {
12
46
  const debugName = `${cyan}[ARKYN-DEBUG]${reset}`;
13
47
  const { callerInfo, functionName } = getCaller();
14
48
 
15
- console.log(`${debugName} ${name} initialized`);
16
- console.log(`${debugName} Caller Function: ${functionName}`);
17
- console.log(`${debugName} Caller Location: ${callerInfo}`);
18
- console.log(`${debugName} Body:`, body);
19
- if (cause) console.log(`[ARKYN-DEBUG] Cause:`, cause);
49
+ let consoleData = `${debugName} ${name} initialized\n`;
50
+ consoleData += `${debugName} Caller Function: ${functionName}\n`;
51
+ consoleData += `${debugName} Caller Location: ${callerInfo}\n`;
52
+ consoleData += `${debugName} Body: ${JSON.stringify(body, null, 2)}\n`;
53
+
54
+ if (cause) {
55
+ consoleData += `${debugName} Cause: ${JSON.stringify(cause, null, 2)}\n`;
56
+ }
57
+
58
+ console.log(consoleData);
59
+ const arkynKeys = InboxFlowInstance.getInboxConfig();
60
+ if (arkynKeys) console.log(arkynKeys);
20
61
  }
21
62
  }
22
63
 
@@ -0,0 +1,5 @@
1
+ import { defineConfig } from "vite";
2
+
3
+ export default defineConfig({
4
+ resolve: { mainFields: ["module"] },
5
+ });
@@ -1,3 +0,0 @@
1
- declare function httpDebug(name: string, body: any, cause?: any): void;
2
- export { httpDebug };
3
- //# sourceMappingURL=httpDebug.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"httpDebug.d.ts","sourceRoot":"","sources":["../../src/http/httpDebug.ts"],"names":[],"mappings":"AAAA,iBAAS,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,QAetD;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -1,15 +0,0 @@
1
- function httpDebug(name, body, cause) {
2
- const isDebugMode = process.env.NODE_ENV === "development" ||
3
- process.env?.SHOW_ERRORS_IN_CONSOLE === "true";
4
- if (isDebugMode) {
5
- const reset = "\x1b[0m";
6
- const cyan = "\x1b[36m";
7
- const pathname = new URL(import.meta.url).pathname;
8
- console.log(`${cyan}[ARKYN-DEBUG]${reset} ${name} initialized`);
9
- console.log(`${cyan}[ARKYN-DEBUG]${reset} Pathname:`, pathname);
10
- console.log(`${cyan}[ARKYN-DEBUG]${reset} Body:`, body);
11
- if (cause)
12
- console.log(`[ARKYN-DEBUG] Cause:`, cause);
13
- }
14
- }
15
- export { httpDebug };