@arkyn/server 3.0.1-beta.116 → 3.0.1-beta.118

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 (178) hide show
  1. package/dist/bundle.js +721 -734
  2. package/dist/bundle.umd.cjs +5 -10
  3. package/dist/{api/arkynLogRequest.d.ts → http/api/_logRequest.d.ts} +22 -19
  4. package/dist/{api/arkynLogRequest.d.ts.map → http/api/_logRequest.d.ts.map} +1 -1
  5. package/dist/{api/arkynLogRequest.js → http/api/_logRequest.js} +30 -30
  6. package/dist/http/api/_makeRequest.d.ts +61 -0
  7. package/dist/http/api/_makeRequest.d.ts.map +1 -0
  8. package/dist/{api/makeRequest.js → http/api/_makeRequest.js} +29 -20
  9. package/dist/http/api/deleteRequest.d.ts +17 -0
  10. package/dist/http/api/deleteRequest.d.ts.map +1 -0
  11. package/dist/http/api/deleteRequest.js +18 -0
  12. package/dist/http/api/getRequest.d.ts +16 -0
  13. package/dist/http/api/getRequest.d.ts.map +1 -0
  14. package/dist/http/api/getRequest.js +17 -0
  15. package/dist/http/api/patchRequest.d.ts +17 -0
  16. package/dist/http/api/patchRequest.d.ts.map +1 -0
  17. package/dist/http/api/patchRequest.js +18 -0
  18. package/dist/http/api/postRequest.d.ts +17 -0
  19. package/dist/http/api/postRequest.d.ts.map +1 -0
  20. package/dist/http/api/postRequest.js +18 -0
  21. package/dist/http/api/putRequest.d.ts +17 -0
  22. package/dist/http/api/putRequest.d.ts.map +1 -0
  23. package/dist/http/api/putRequest.js +18 -0
  24. package/dist/http/badResponses/_badResponse.d.ts +18 -7
  25. package/dist/http/badResponses/_badResponse.d.ts.map +1 -1
  26. package/dist/http/badResponses/_badResponse.js +44 -13
  27. package/dist/http/badResponses/badGateway.d.ts +4 -8
  28. package/dist/http/badResponses/badGateway.d.ts.map +1 -1
  29. package/dist/http/badResponses/badGateway.js +9 -17
  30. package/dist/http/badResponses/badRequest.d.ts +4 -8
  31. package/dist/http/badResponses/badRequest.d.ts.map +1 -1
  32. package/dist/http/badResponses/badRequest.js +9 -17
  33. package/dist/http/badResponses/conflict.d.ts +4 -8
  34. package/dist/http/badResponses/conflict.d.ts.map +1 -1
  35. package/dist/http/badResponses/conflict.js +9 -17
  36. package/dist/http/badResponses/forbidden.d.ts +4 -8
  37. package/dist/http/badResponses/forbidden.d.ts.map +1 -1
  38. package/dist/http/badResponses/forbidden.js +9 -17
  39. package/dist/http/badResponses/notFound.d.ts +4 -8
  40. package/dist/http/badResponses/notFound.d.ts.map +1 -1
  41. package/dist/http/badResponses/notFound.js +9 -17
  42. package/dist/http/badResponses/notImplemented.d.ts +4 -8
  43. package/dist/http/badResponses/notImplemented.d.ts.map +1 -1
  44. package/dist/http/badResponses/notImplemented.js +9 -17
  45. package/dist/http/badResponses/serverError.d.ts +4 -8
  46. package/dist/http/badResponses/serverError.d.ts.map +1 -1
  47. package/dist/http/badResponses/serverError.js +9 -17
  48. package/dist/http/badResponses/unauthorized.d.ts +2 -6
  49. package/dist/http/badResponses/unauthorized.d.ts.map +1 -1
  50. package/dist/http/badResponses/unauthorized.js +7 -15
  51. package/dist/http/badResponses/unprocessableEntity.d.ts +13 -18
  52. package/dist/http/badResponses/unprocessableEntity.d.ts.map +1 -1
  53. package/dist/http/badResponses/unprocessableEntity.js +14 -22
  54. package/dist/http/successResponses/_successResponse.d.ts +18 -7
  55. package/dist/http/successResponses/_successResponse.d.ts.map +1 -1
  56. package/dist/http/successResponses/_successResponse.js +50 -21
  57. package/dist/http/successResponses/created.d.ts +8 -22
  58. package/dist/http/successResponses/created.d.ts.map +1 -1
  59. package/dist/http/successResponses/created.js +13 -25
  60. package/dist/http/successResponses/found.d.ts +9 -26
  61. package/dist/http/successResponses/found.d.ts.map +1 -1
  62. package/dist/http/successResponses/found.js +14 -29
  63. package/dist/http/successResponses/noContent.d.ts +4 -12
  64. package/dist/http/successResponses/noContent.d.ts.map +1 -1
  65. package/dist/http/successResponses/noContent.js +9 -17
  66. package/dist/http/successResponses/success.d.ts +8 -22
  67. package/dist/http/successResponses/success.d.ts.map +1 -1
  68. package/dist/http/successResponses/success.js +13 -25
  69. package/dist/http/successResponses/updated.d.ts +8 -22
  70. package/dist/http/successResponses/updated.d.ts.map +1 -1
  71. package/dist/http/successResponses/updated.js +13 -25
  72. package/dist/index.d.ts +9 -10
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +11 -12
  75. package/dist/services/apiService.d.ts +7 -28
  76. package/dist/services/apiService.d.ts.map +1 -1
  77. package/dist/services/apiService.js +35 -41
  78. package/dist/services/debugService.d.ts +16 -1
  79. package/dist/services/debugService.d.ts.map +1 -1
  80. package/dist/services/debugService.js +58 -1
  81. package/dist/services/logMapperService.d.ts +86 -0
  82. package/dist/services/logMapperService.d.ts.map +1 -0
  83. package/dist/services/logMapperService.js +68 -0
  84. package/dist/services/logService.d.ts +38 -0
  85. package/dist/services/logService.d.ts.map +1 -0
  86. package/dist/services/logService.js +40 -0
  87. package/dist/{services → utilities}/decodeRequestBody.d.ts +3 -4
  88. package/dist/utilities/decodeRequestBody.d.ts.map +1 -0
  89. package/dist/{services → utilities}/decodeRequestBody.js +5 -5
  90. package/dist/{services/decodeErrorMessageFromRequest.d.ts → utilities/decodeRequestErrorMessage.d.ts} +6 -6
  91. package/dist/utilities/decodeRequestErrorMessage.d.ts.map +1 -0
  92. package/dist/{services/decodeErrorMessageFromRequest.js → utilities/decodeRequestErrorMessage.js} +5 -5
  93. package/dist/utilities/errorHandler.d.ts +50 -0
  94. package/dist/utilities/errorHandler.d.ts.map +1 -0
  95. package/dist/{services → utilities}/errorHandler.js +34 -28
  96. package/dist/utilities/flushDebugLogs.d.ts +46 -0
  97. package/dist/utilities/flushDebugLogs.d.ts.map +1 -0
  98. package/dist/utilities/flushDebugLogs.js +59 -0
  99. package/dist/{services → utilities}/formAsyncParse.d.ts +3 -3
  100. package/dist/utilities/formAsyncParse.d.ts.map +1 -0
  101. package/dist/{services → utilities}/formAsyncParse.js +3 -3
  102. package/dist/{services → utilities}/formParse.d.ts +3 -3
  103. package/dist/utilities/formParse.d.ts.map +1 -0
  104. package/dist/{services → utilities}/formParse.js +3 -3
  105. package/dist/{services → utilities}/getScopedParams.d.ts +3 -4
  106. package/dist/utilities/getScopedParams.d.ts.map +1 -0
  107. package/dist/{services → utilities}/getScopedParams.js +4 -4
  108. package/dist/{services → utilities}/schemaValidator.d.ts +3 -15
  109. package/dist/utilities/schemaValidator.d.ts.map +1 -0
  110. package/dist/{services → utilities}/schemaValidator.js +3 -19
  111. package/dist/validations/validateCep.d.ts +7 -12
  112. package/dist/validations/validateCep.d.ts.map +1 -1
  113. package/dist/validations/validateCep.js +9 -15
  114. package/dist/validations/validateCnpj.d.ts +4 -5
  115. package/dist/validations/validateCnpj.d.ts.map +1 -1
  116. package/dist/validations/validateCnpj.js +12 -5
  117. package/dist/validations/validateCpf.d.ts +3 -4
  118. package/dist/validations/validateCpf.d.ts.map +1 -1
  119. package/dist/validations/validateCpf.js +11 -4
  120. package/dist/validations/validateDate.d.ts +16 -23
  121. package/dist/validations/validateDate.d.ts.map +1 -1
  122. package/dist/validations/validateDate.js +38 -56
  123. package/dist/validations/validateEmail.d.ts +3 -4
  124. package/dist/validations/validateEmail.d.ts.map +1 -1
  125. package/dist/validations/validateEmail.js +23 -35
  126. package/dist/validations/validatePassword.d.ts +3 -4
  127. package/dist/validations/validatePassword.d.ts.map +1 -1
  128. package/dist/validations/validatePassword.js +5 -5
  129. package/dist/validations/validatePhone.d.ts +3 -4
  130. package/dist/validations/validatePhone.d.ts.map +1 -1
  131. package/dist/validations/validatePhone.js +4 -4
  132. package/dist/validations/validateRg.d.ts +3 -4
  133. package/dist/validations/validateRg.d.ts.map +1 -1
  134. package/dist/validations/validateRg.js +4 -4
  135. package/package.json +1 -1
  136. package/dist/api/deleteRequest.d.ts +0 -13
  137. package/dist/api/deleteRequest.d.ts.map +0 -1
  138. package/dist/api/deleteRequest.js +0 -14
  139. package/dist/api/getRequest.d.ts +0 -12
  140. package/dist/api/getRequest.d.ts.map +0 -1
  141. package/dist/api/getRequest.js +0 -13
  142. package/dist/api/makeRequest.d.ts +0 -38
  143. package/dist/api/makeRequest.d.ts.map +0 -1
  144. package/dist/api/patchRequest.d.ts +0 -13
  145. package/dist/api/patchRequest.d.ts.map +0 -1
  146. package/dist/api/patchRequest.js +0 -14
  147. package/dist/api/postRequest.d.ts +0 -13
  148. package/dist/api/postRequest.d.ts.map +0 -1
  149. package/dist/api/postRequest.js +0 -14
  150. package/dist/api/putRequest.d.ts +0 -13
  151. package/dist/api/putRequest.d.ts.map +0 -1
  152. package/dist/api/putRequest.js +0 -14
  153. package/dist/mapper/arkynLogRequestMapper.d.ts +0 -30
  154. package/dist/mapper/arkynLogRequestMapper.d.ts.map +0 -1
  155. package/dist/mapper/arkynLogRequestMapper.js +0 -44
  156. package/dist/services/arkynLogService.d.ts +0 -44
  157. package/dist/services/arkynLogService.d.ts.map +0 -1
  158. package/dist/services/arkynLogService.js +0 -46
  159. package/dist/services/decodeErrorMessageFromRequest.d.ts.map +0 -1
  160. package/dist/services/decodeRequestBody.d.ts.map +0 -1
  161. package/dist/services/errorHandler.d.ts +0 -44
  162. package/dist/services/errorHandler.d.ts.map +0 -1
  163. package/dist/services/flushDebugLogs.d.ts +0 -8
  164. package/dist/services/flushDebugLogs.d.ts.map +0 -1
  165. package/dist/services/flushDebugLogs.js +0 -20
  166. package/dist/services/formAsyncParse.d.ts.map +0 -1
  167. package/dist/services/formParse.d.ts.map +0 -1
  168. package/dist/services/getCaller.d.ts +0 -17
  169. package/dist/services/getCaller.d.ts.map +0 -1
  170. package/dist/services/getCaller.js +0 -60
  171. package/dist/services/getScopedParams.d.ts.map +0 -1
  172. package/dist/services/measureRouteExecution.d.ts +0 -3
  173. package/dist/services/measureRouteExecution.d.ts.map +0 -1
  174. package/dist/services/measureRouteExecution.js +0 -24
  175. package/dist/services/schemaValidator.d.ts.map +0 -1
  176. package/dist/types/ApiResponseDTO.d.ts +0 -17
  177. package/dist/types/ApiResponseDTO.d.ts.map +0 -1
  178. package/dist/types/ApiResponseDTO.js +0 -1
@@ -1,10 +1,5 @@
1
- (function(u,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("zod"),require("@arkyn/shared"),require("node:dns"),require("@arkyn/templates")):typeof define=="function"&&define.amd?define(["exports","zod","@arkyn/shared","node:dns","@arkyn/templates"],f):(u=typeof globalThis<"u"?globalThis:u||self,f(u["@arkyn/server"]={},null,u.shared,null,u.templates))})(this,function(u,f,m,js,Y){"use strict";var $s=Object.defineProperty;var Is=(u,f,m)=>f in u?$s(u,f,{enumerable:!0,configurable:!0,writable:!0,value:m}):u[f]=m;var o=(u,f,m)=>Is(u,typeof f!="symbol"?f+"":f,m);function b(e){var s;if(process.env.NODE_ENV==="development"||((s=process.env)==null?void 0:s.SHOW_ERRORS_IN_CONSOLE)==="true"){const a=`${{yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m",green:"\x1B[32m"}[e.scheme]}[${e.name}]\x1B[0m`;let h=`
2
- `;e.debugs.forEach(l=>{h+=`${a} ${l.trim()}
3
- `}),console.log(h)}}const _={};class D{static setIgnoreFile(n){this.ignoreFiles.push(n)}static clearIgnoreFiles(){this.ignoreFiles=[]}}o(D,"ignoreFiles",[]);function N(){const e=process.cwd(),t=(new Error().stack||"").split(`
4
- `).map(i=>i.trim()),r=D.ignoreFiles;let a=2;for(;a<t.length&&(t[a].includes("node:internal")||t[a].includes("/node_modules/"));)a++;if(r.length>0)for(;a<t.length&&r.some(i=>t[a].includes(i));)a++;const h=t[a]||"";let l="Unknown function",c="Unknown caller";const d=h.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);if(d)l=d[1],c=d[2];else{const i=h.match(/at\s+(.+)/);if(i){c=i[1];const p=c.match(/at\s+([^(\s]+)\s+/);p&&p[1]!=="new"&&(l=p[1])}}c.includes("(")&&(c=c.substring(c.indexOf("(")+1,c.lastIndexOf(")"))),c=c.split(":").slice(0,-2).join(":");try{c=_.relative(e,c)}catch{}return{functionName:l,callerInfo:c}}class g{onDebug(n){const{name:s,body:t,cause:r,message:a}=n,h=[],{callerInfo:l,functionName:c}=N();h.push(`${s} initialized`),h.push(`Caller Function: ${c}`),h.push(`Caller Location: ${l}`),a&&h.push(`Message: ${a}`),t&&h.push(`Body: ${JSON.stringify(t,null,2)}`),r&&h.push(`Cause: ${JSON.stringify(r,null,2)}`),b({scheme:"red",name:"ARKYN-BAD-RESPONSE-DEBUG",debugs:h})}}class C extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",502);o(this,"statusText");this.body={name:"BadGateway",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"BadGateway",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class S extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",400);o(this,"statusText");this.body={name:"BadRequest",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"BadRequest",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class $ extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",409);o(this,"statusText");this.body={name:"Conflict",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"Conflict",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class I extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",403);o(this,"statusText");this.body={name:"Forbidden",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"Forbidden",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class j extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",404);o(this,"statusText");this.body={name:"NotFound",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"NotFound",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class J extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",501);o(this,"statusText");this.body={name:"NotImplemented",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"NotImplemented",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class E extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",500);o(this,"statusText");this.body={name:"ServerError",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"ServerError",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class U extends g{constructor(s,t){super();o(this,"body");o(this,"cause");o(this,"status",401);o(this,"statusText");this.body={name:"Unauthorized",message:s},this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug({name:"Unauthorized",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class O extends g{constructor(s){super();o(this,"body");o(this,"status",422);o(this,"statusText");this.statusText=s.message||"Unprocessable Entity",this.body={name:"UnprocessableEntity",message:s.message||null,data:s.data,fieldErrors:s.fieldErrors,fields:s.fields},this.onDebug({name:"UnprocessableEntity",cause:s.fieldErrors,message:s.message})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class R{onDebug(n,s,t){const r=[],{callerInfo:a,functionName:h}=N();r.push(`${n} initialized
5
- `),r.push(`Caller Function: ${h}
6
- `),r.push(`Caller Location: ${a}
7
- `),r.push(`Body: ${JSON.stringify(s,null,2)}
8
- `),t&&r.push(`Cause: ${JSON.stringify(t,null,2)}
9
- `),b({scheme:"green",name:"ARKYN-SUCCESS-RESPONSE-DEBUG",debugs:r})}}class w extends R{constructor(s,t){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body={...s,name:"Created",message:t==null?void 0:t.message},this.headers=(t==null?void 0:t.headers)||{},this.status=(t==null?void 0:t.status)||201,this.statusText=(t==null?void 0:t.statusText)||"Resource created successfully",this.onDebug("Created",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class A extends R{constructor(s,t){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body={...s,name:"Found",message:t==null?void 0:t.message},this.headers=(t==null?void 0:t.headers)||{},this.status=(t==null?void 0:t.status)||302,this.statusText=(t==null?void 0:t.statusText)||"Found",this.onDebug("Found",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class q extends R{constructor(s){super();o(this,"headers");o(this,"status");o(this,"statusText");this.headers=(s==null?void 0:s.headers)||{},this.status=(s==null?void 0:s.status)||204,this.statusText=(s==null?void 0:s.statusText)??"No content",this.onDebug("No content",null)}toResponse(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return new Response(null,s)}}class k extends R{constructor(s,t){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body={...s,name:"Success",message:t==null?void 0:t.message},this.headers=(t==null?void 0:t.headers)||{},this.status=(t==null?void 0:t.status)||200,this.statusText=(t==null?void 0:t.statusText)??"OK",this.onDebug("Success",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class B extends R{constructor(s,t){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body={...s,name:"Updated",message:t==null?void 0:t.message},this.headers=(t==null?void 0:t.headers)||{},this.status=(t==null?void 0:t.status)||200,this.statusText=(t==null?void 0:t.statusText)||"Resource updated successfully",this.onDebug("Updated",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class V{static mapHeaders(n){return n instanceof Headers?Object.fromEntries(n.entries()):typeof n=="object"?Object.entries(n).reduce((s,[t,r])=>(typeof r=="string"?s[t]=r:Array.isArray(r)?s[t]=r.join(", "):s[t]=JSON.stringify(r),s),{}):{}}static mapQueryParams(n){const s={};return n.forEach((t,r)=>{s[r]=t}),s}static handle(n){return{rawUrl:n.url,status:n.status,method:n.method,token:null,elapsedTime:n.elapsedTime,requestHeaders:this.mapHeaders(n.requestHeaders),requestBody:n.requestBody||null,queryParams:this.mapQueryParams(n.queryParams),responseHeaders:this.mapHeaders(n.responseHeaders),responseBody:n.responseBody||null}}}class v{static setArkynConfig(n){if(this.arkynConfig)return;const{trafficSourceId:s,userToken:t,logBaseApiUrl:r}=n;this.arkynConfig={trafficSourceId:s,userToken:t,apiUrl:r||"http://95.216.190.158:8081/ingest-log"}}static getArkynConfig(){return this.arkynConfig}static resetArkynConfig(){this.arkynConfig=void 0}}o(v,"arkynConfig");async function G(e){const n=v.getArkynConfig();if(!n)return;const{userToken:s,apiUrl:t,trafficSourceId:r}=n,{elapsedTime:a,method:h,queryParams:l,requestBody:c,requestHeaders:d,responseBody:i,responseHeaders:p,status:z,token:y,rawUrl:vs}=e;if(process.env.NODE_ENV!=="development")try{const T=new URL(vs);let M="https";T.protocol==="http:"&&(M="http");const Cs=JSON.stringify({domainUrl:T.protocol+"//"+T.host,pathnameUrl:T.pathname,trafficSourceId:r,status:z,protocol:M,method:h.toLowerCase(),trafficUserId:null,elapsedTime:a,requestHeaders:JSON.stringify(d),requestBody:JSON.stringify(c),queryParams:JSON.stringify(l),responseHeaders:JSON.stringify(p),responseBody:JSON.stringify(i)});await fetch(t,{method:"POST",body:Cs,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(T){b({debugs:[`Error sending request: ${T}`],name:"ARKYN_LOG_ERROR",scheme:"red"})}}async function x(e,n,s={},t){const r={POST:"Resource created successfully",PUT:"Resource updated successfully",DELETE:"Resource deleted successfully",PATCH:"Resource patched successfully",GET:"Request successful"};try{const a=performance.now(),h={...s,"Content-Type":"application/json"},l=await fetch(n,{method:e,headers:h,body:t?JSON.stringify(t):void 0}),c=performance.now()-a,d=l.status;let i=null;try{i=await l.json()}catch{i=null}const p=V.handle({elapsedTime:c,method:e,queryParams:new URL(n).searchParams,requestHeaders:h,requestBody:t,responseBody:i,responseHeaders:l.headers,status:d,url:n});return G(p),l.ok?{success:!0,status:d,message:(i==null?void 0:i.message)||r[e],response:i,cause:null}:{success:!1,status:d,message:(i==null?void 0:i.message)||l.statusText||"Request failed",response:i,cause:null}}catch(a){return b({debugs:[`Network error or request failed: ${a}`],name:"ARKYN_MAKE_REQUEST_ERROR",scheme:"red"}),{success:!1,status:0,message:"Network error or request failed",response:null,cause:a instanceof Error?a.message:String(a)}}}async function Z(e,n={},s){return x("DELETE",e,n,s)}async function W(e,n={}){return x("GET",e,n)}async function K(e,n={},s){return x("PATCH",e,n,s)}async function Q(e,n={},s){return x("POST",e,n,s)}async function X(e,n={},s){return x("PUT",e,n,s)}class ss{constructor(n){o(this,"baseUrl");o(this,"baseHeaders");o(this,"baseToken");o(this,"enableDebug");this.baseUrl=n.baseUrl,this.baseHeaders=n.baseHeaders||void 0,this.baseToken=n.baseToken||void 0,this.enableDebug=n.enableDebug||!1}onDebug(n,s,t){if(this.enableDebug){const r=[];r.push(`Base URL: ${this.baseUrl}`),r.push(`Endpoint: ${n}`),r.push(`Method: ${s}`),t[0]&&r.push(`Headers: ${JSON.stringify(t[0])}`),t[1]&&r.push(`Body: ${JSON.stringify(t[1])}`),b({debugs:r,name:"ARKYN-API-DEBUG",scheme:"yellow"})}}generateURL(n){return this.baseUrl+n}generateHeaders(n,s){let t={};return this.baseToken&&(t={Authorization:`Bearer ${this.baseToken}`}),this.baseHeaders&&(t={...t,...this.baseHeaders}),n&&(t={...t,...n}),s&&(t={...t,Authorization:`Bearer ${s}`}),t}async get(n,s){const t=this.generateURL(n),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token);return this.onDebug(n,"get",[r]),await W(t,r)}async post(n,s){const t=this.generateURL(n),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(n,"post",[r,a]),await Q(t,r,a)}async put(n,s){const t=this.generateURL(n),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(n,"put",[r,a]),await X(t,r,a)}async patch(n,s){const t=this.generateURL(n),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(n,"patch",[r,a]),await K(t,r,a)}async delete(n,s){const t=this.generateURL(n),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(n,"delete",[r,a]),await Z(t,r,a)}}function es(e,n){var s,t,r;return e!=null&&e.message&&typeof(e==null?void 0:e.message)=="string"?e==null?void 0:e.message:e!=null&&e.error&&typeof(e==null?void 0:e.error)=="string"?e==null?void 0:e.error:(s=e==null?void 0:e.error)!=null&&s.message&&typeof((t=e==null?void 0:e.error)==null?void 0:t.message)=="string"?(r=e==null?void 0:e.error)==null?void 0:r.message:n!=null&&n.statusText&&typeof(n==null?void 0:n.statusText)=="string"?n==null?void 0:n.statusText:"Missing error message"}const ts=async e=>{let n;const s=await e.arrayBuffer(),t=new TextDecoder().decode(s);try{n=JSON.parse(t)}catch{try{if(t.includes("=")){const a=new URLSearchParams(t);n=Object.fromEntries(a.entries())}else throw new S("Invalid URLSearchParams format")}catch{throw new S("Failed to extract data from request")}}return n};function ns(e){switch(!0){case e instanceof Response:return e;case e instanceof A:return e.toResponse();case e instanceof w:return e.toResponse();case e instanceof B:return e.toResponse();case e instanceof k:return e.toResponse();case e instanceof q:return e.toResponse()}switch(!0){case e instanceof C:return e.toResponse();case e instanceof S:return e.toResponse();case e instanceof $:return e.toResponse();case e instanceof I:return e.toResponse();case e instanceof j:return e.toResponse();case e instanceof J:return e.toResponse();case e instanceof E:return e.toResponse();case e instanceof U:return e.toResponse();case e instanceof O:return e.toResponse()}return new E("Server error",e).toResponse()}async function L([e,n]){const s=await n.safeParseAsync(e);if(s.success===!1){const t=Object.fromEntries(s.error.issues.map(r=>[r.path.join("."),r.message]));return{success:s.success,fieldErrors:t,fields:e}}else return{success:s.success,data:s.data}}function F([e,n]){const s=n.safeParse(e);if(s.success===!1){const t=Object.fromEntries(s.error.issues.map(r=>[r.path.join("."),r.message]));return{success:s.success,fieldErrors:t,fields:e}}else return{success:s.success,data:s.data}}const rs=(e,n="")=>{const s=new URL(e.url);if(n==="")return s.searchParams;const t=Array.from(s.searchParams.entries()).filter(([r])=>r.startsWith(`${n}:`)).map(([r,a])=>[r.replace(`${n}:`,""),a]);return new URLSearchParams(t)};function os(e){const n="Error validating:",s=e.issues.map(({path:t,message:r})=>`-> ${t.join(".")}: ${r}`);return[n,...s].join(`
10
- `)}class as{constructor(n){o(this,"functionName");o(this,"callerInfo");this.schema=n;const{callerInfo:s,functionName:t}=N();this.callerInfo=s,this.functionName=t}isValid(n){return this.schema.safeParse(n).success}safeValidate(n){return this.schema.safeParse(n)}validate(n){try{return this.schema.parse(n)}catch(s){throw new E(os(s))}}formValidate(n,s){const t=F([n,this.schema]);if(!t.success){const r=Object.keys(t.fieldErrors)[0];throw new O({fields:t.fields,fieldErrors:t.fieldErrors,data:{scrollTo:r},message:s})}return t.data}async formAsyncValidate(n,s){const t=await L([n,this.schema]);if(!t.success){const r=Object.keys(t.fieldErrors)[0];throw new O({fields:t.fields,fieldErrors:t.fieldErrors,data:{scrollTo:r},message:s})}return t.data}}const us=e=>{if(!e||!/^[0-9-]+$/.test(e))return!1;const s=m.removeNonNumeric(e),t=8,r=/^\d{8}$/.test(s);return s.length===t&&r};function is(e){return e.length!==14}function cs(e){const[n]=e;return[...e].every(s=>s===n)}function H(e,n){let s=0;for(let r=0;r<n.length;r++)s+=parseInt(e[r])*n[r];const t=s%11;return t<2?0:11-t}function hs(e){return e.slice(12)}const ls=e=>{if(!e)return!1;const n=m.removeNonNumeric(e);if(is(n)||cs(n))return!1;const s=n.slice(0,12),t=H(s,[5,4,3,2,9,8,7,6,5,4,3,2]),r=H(s+t,[6,5,4,3,2,9,8,7,6,5,4,3,2]);return hs(n)===`${t}${r}`};function ds(e){return e.length!==11}function fs(e){const[n]=e;return[...e].every(s=>s===n)}function P(e,n){let s=0;for(const r of e)n>1&&(s+=parseInt(r)*n--);const t=s%11;return t<2?0:11-t}function ys(e){return e.slice(9)}const gs=e=>{if(!e)return!1;const n=m.removeNonNumeric(e);if(ds(n)||fs(n))return!1;const s=P(n,10),t=P(n,11);return ys(n)===`${s}${t}`},ps=(e,n)=>{let s,t,r;const a=(n==null?void 0:n.inputFormat)||"DD/MM/YYYY",h=(n==null?void 0:n.minYear)||1900,l=(n==null?void 0:n.maxYear)||3e3;if(a==="DD/MM/YYYY"){const y=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!y.test(e))return!1;[,s,t,r]=e.match(y)||[]}else if(a==="MM-DD-YYYY"){const y=/^(\d{2})-(\d{2})-(\d{4})$/;if(!y.test(e))return!1;[,t,s,r]=e.match(y)||[]}else if(a==="YYYY-MM-DD"){const y=/^(\d{4})-(\d{2})-(\d{2})$/;if(!y.test(e))return!1;[,r,t,s]=e.match(y)||[]}else throw new Error("Invalid date format");const c=parseInt(s,10),d=parseInt(t,10),i=parseInt(r,10);if(c<1||c>31||d<1||d>12)return!1;const p=[31,28,31,30,31,30,31,31,30,31,30,31];if(d===2){const y=i%4===0&&i%100!==0||i%400===0;if(c>(y?29:28))return!1}else if(c>p[d-1])return!1;return i<h||i>l?!1:new Date(i,d-1,c).getDate()===c};function ms(e){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e)}function bs(e){return!(e.length===0||e.length>64||e.startsWith(".")||e.endsWith(".")||e.includes("..")||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(e))}function Ts(e){return!(e.length===0||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-zA-Z0-9-]+$/.test(e))}function Rs(e){if(e.length===0||e.length>253||e.startsWith(".")||e.endsWith(".")||e.startsWith("-")||e.endsWith("-"))return!1;const n=e.split(".");if(n.length<2)return!1;for(const t of n)if(!Ts(t))return!1;const s=n[n.length-1];return!(s.length<2||!/^[a-zA-Z]+$/.test(s))}function xs(e){const n=e.split("@");if(n.length!==2)return!1;const[s,t]=n;return!(!bs(s)||!Rs(t))}function Ns(e){const n=e.split("@");return n.length===2?n[1].toLowerCase():null}const Ss=async e=>{if(!e||typeof e!="string")return!1;const n=e.trim();return!(!ms(n)||!xs(n)||!Ns(n))},Es=e=>{if(!e)return!1;const n=e.length>=8,s=/[A-Z]/.test(e),t=/[a-z]/.test(e),r=/\d/.test(e),a=/[!@#$%^&*(),.?":{}|<>_\-+=~`[\]\\\/]/.test(e);return[n,s,t,r,a].every(h=>h)},Os=e=>{for(const n of Y.countries){const s=n.code,t=n.prefix?`-${n.prefix}`:"",r=n.mask.replace(/[^_]/g,"").length;if(n.iso==="BR"){if(new RegExp(`^\\${s} \\d{2}9?\\d{8}$`).test(e))return!0;continue}if(new RegExp(`^\\${s}${t} \\d{${r}}$`).test(e))return!0}return!1},Ds=e=>{if(!e||!/^[0-9a-zA-Z.-]+$/.test(e))return!1;const s=e.replace(/[^a-zA-Z0-9]/g,"");return s.length<7||s.length>9?!1:/^[0-9]{7,8}[0-9Xx]?$/.test(s)};u.ApiService=ss,u.ArkynLogService=v,u.BadGateway=C,u.BadRequest=S,u.Conflict=$,u.Created=w,u.DebugService=D,u.Forbidden=I,u.Found=A,u.NoContent=q,u.NotFound=j,u.NotImplemented=J,u.SchemaValidator=as,u.ServerError=E,u.Success=k,u.Unauthorized=U,u.UnprocessableEntity=O,u.Updated=B,u.decodeErrorMessageFromRequest=es,u.decodeRequestBody=ts,u.errorHandler=ns,u.flushDebugLogs=b,u.formAsyncParse=L,u.formParse=F,u.getCaller=N,u.getScopedParams=rs,u.validateCep=us,u.validateCnpj=ls,u.validateCpf=gs,u.validateDate=ps,u.validateEmail=Ss,u.validatePassword=Es,u.validatePhone=Os,u.validateRg=Ds,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
1
+ (function(i,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("zod"),require("@arkyn/shared"),require("node:dns"),require("@arkyn/templates")):typeof define=="function"&&define.amd?define(["exports","zod","@arkyn/shared","node:dns","@arkyn/templates"],h):(i=typeof globalThis<"u"?globalThis:i||self,h(i["@arkyn/server"]={},null,i.shared,i.dns,i.templates))})(this,function(i,h,d,D,L){"use strict";var ws=Object.defineProperty;var js=(i,h,d)=>h in i?ws(i,h,{enumerable:!0,configurable:!0,writable:!0,value:d}):i[h]=d;var l=(i,h,d)=>js(i,typeof h!="symbol"?h+"":h,d);const z={};class x{static setIgnoreFile(s){this.ignoreFiles.push(s)}static clearIgnoreFiles(){this.ignoreFiles=[]}static getCaller(){const s=process.cwd(),r=(new Error().stack||"").split(`
2
+ `).map(y=>y.trim());let a=2;for(;a<r.length&&(r[a].includes("node:internal")||r[a].includes("/node_modules/"));)a++;if(this.ignoreFiles.length>0)for(;a<r.length&&this.ignoreFiles.some(y=>r[a].includes(y));)a++;const u=r[a]||"";let c="Unknown function",o="Unknown caller";const f=u.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);if(f)c=f[1],o=f[2];else{const y=u.match(/at\s+(.+)/);if(y){o=y[1];const R=o.match(/at\s+([^(\s]+)\s+/);R&&R[1]!=="new"&&(c=R[1])}}o.includes("(")&&(o=o.substring(o.indexOf("(")+1,o.lastIndexOf(")"))),o=o.split(":").slice(0,-2).join(":");try{o=z.relative(s,o)}catch{}return{functionName:c,callerInfo:o}}}l(x,"ignoreFiles",[]);function g(e){var t;if(process.env.NODE_ENV==="development"||((t=process.env)==null?void 0:t.DEBUG_MODE)==="true"){const a=`${{yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m",green:"\x1B[32m"}[e.scheme]}[${e.name}]\x1B[0m`;let u=`
3
+ `;e.debugs.forEach(c=>{u+=`${a} ${c.trim()}
4
+ `}),console.log(u)}}class m{constructor(){l(this,"_cause");l(this,"_name","BadResponse");l(this,"_status",500);l(this,"_statusText","Unknown error")}get cause(){return this._cause}set cause(s){this._cause=s}get name(){return this._name}set name(s){this._name=s}get status(){return this._status}set status(s){this._status=s}get statusText(){return this._statusText}set statusText(s){this._statusText=s}onDebug(){const s=[],{callerInfo:t,functionName:n}=x.getCaller();s.push(`Caller Function: ${n}`),s.push(`Caller Location: ${t}`),this._statusText&&s.push(`Message: ${this._statusText}`),this._cause&&s.push(`Cause: ${JSON.stringify(this._cause)}`),g({scheme:"red",name:this._name,debugs:s})}makeBody(){return{name:this._name,message:this._statusText,cause:this._cause}}}class P extends m{constructor(s,t){super(),this.name="BadGateway",this.status=502,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class S extends m{constructor(s,t){super(),this.name="BadRequest",this.status=400,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class B extends m{constructor(s,t){super(),this.name="Conflict",this.status=409,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class O extends m{constructor(s,t){super(),this.name="Forbidden",this.status=403,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class $ extends m{constructor(s,t){super(),this.name="NotFound",this.status=404,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class k extends m{constructor(s,t){super(),this.name="NotImplemented",this.status=501,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class v extends m{constructor(s,t){super(),this.name="ServerError",this.status=500,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class w extends m{constructor(s,t){super(),this.name="Unauthorized",this.status=401,this.statusText=s,this.cause=t?JSON.stringify(t):void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class N extends m{constructor(s){super(),this.name="UnprocessableEntity",this.status=422,this.statusText=s.message||"Unprocessable entity",this.cause={data:s.data,fieldErrors:s.fieldErrors,fields:s.fields},this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.makeBody()),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.makeBody(),s)}}class T{constructor(){l(this,"_body",null);l(this,"_name","SuccessResponse");l(this,"_status",200);l(this,"_statusText","OK")}get body(){return this._body}set body(s){this._body=s??null}get name(){return this._name}set name(s){this._name=s}get status(){return this._status}set status(s){this._status=s}get statusText(){return this._statusText}set statusText(s){this._statusText=s}onDebug(s){const t=[],{callerInfo:n,functionName:r}=x.getCaller();t.push(`Caller Function: ${r}`),t.push(`Caller Location: ${n}`),this.statusText&&t.push(`Message: ${this.statusText}`),s&&t.push(`Body: ${JSON.stringify(s)}`),g({scheme:"red",name:this.name,debugs:t})}makeBody(){return{name:this.name,message:this.statusText,body:this.body}}}class j extends T{constructor(s,t){super(),this.name="Created",this.status=201,this.statusText=s,this.body=t||void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class J extends T{constructor(s,t){super(),this.name="Found",this.status=302,this.statusText=s,this.body=t||void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class C extends T{constructor(s){super(),this.name="NoContent",this.status=204,this.statusText=s,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(null,s)}}class I extends T{constructor(s,t){super(),this.name="Success",this.status=200,this.statusText=s,this.body=t||void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class _ extends T{constructor(s,t){super(),this.name="Updated",this.status=200,this.statusText=s,this.body=t||void 0,this.onDebug()}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class M{static mapHeaders(s){return s instanceof Headers?Object.fromEntries(s.entries()):typeof s=="object"?Object.entries(s).reduce((t,[n,r])=>(typeof r=="string"?t[n]=r:Array.isArray(r)?t[n]=r.join(", "):t[n]=JSON.stringify(r),t),{}):{}}static mapQueryParams(s){const t={};return s.forEach((n,r)=>t[r]=n),t}static handle(s){return{rawUrl:s.rawUrl,status:s.status,method:s.method,token:null,elapsedTime:s.elapsedTime,requestHeaders:this.mapHeaders(s.requestHeaders),requestBody:s.requestBody||null,queryParams:{...this.mapQueryParams(s.queryParams),...s.urlParams},responseHeaders:this.mapHeaders(s.responseHeaders),responseBody:s.responseBody||null}}}class E{static setConfig(s){if(this.config)return;const{trafficSourceId:t,userToken:n,logBaseApiUrl:r}=s,u=`${r||"http://95.216.190.158:8081"}/ingest-log`;this.config={trafficSourceId:t,userToken:n,apiUrl:u}}static getConfig(){return this.config}static resetConfig(){this.config=void 0}}l(E,"config");async function V(e){const s=E.getConfig();if(!s)return;const{userToken:t,apiUrl:n,trafficSourceId:r}=s,{elapsedTime:a,method:u,queryParams:c,requestBody:o,requestHeaders:f,responseBody:y,responseHeaders:R,status:Bs,token:Js,rawUrl:Os}=e;if(process.env.NODE_ENV!=="development")try{const p=new URL(Os);let F="https";p.protocol==="http:"&&(F="http");const $s=JSON.stringify({domainUrl:p.protocol+"//"+p.host,pathnameUrl:p.pathname,trafficSourceId:r,status:Bs,protocol:F,method:u.toLowerCase(),trafficUserId:null,elapsedTime:a,requestHeaders:JSON.stringify(f),requestBody:JSON.stringify(o),queryParams:JSON.stringify(c),responseHeaders:JSON.stringify(R),responseBody:JSON.stringify(y)}),ks={"Content-Type":"application/json",Authorization:`Bearer ${t}`};await fetch(n,{method:"POST",body:$s,headers:ks})}catch(p){g({debugs:[`Error sending request: ${p}`],name:"LogError",scheme:"red"})}}async function b(e){let s=e.url;e.urlParams&&Object.entries(e.urlParams).forEach(([n,r])=>{s=s.replaceAll(`:${n}`,r)});const t={POST:"Resource created successfully",PUT:"Resource updated successfully",DELETE:"Resource deleted successfully",PATCH:"Resource patched successfully",GET:"Request successful"};try{const n=performance.now(),r={...e.headers,"Content-Type":"application/json"},a=await fetch(s,{headers:r,method:e.method,body:e.body?JSON.stringify(e.body):void 0}),u=performance.now()-n,c=a.status;let o=null;try{o=await a.json()}catch{o=null}const f=M.handle({elapsedTime:u,method:e.method,queryParams:new URL(s).searchParams,requestHeaders:r,requestBody:e.body,responseBody:o,responseHeaders:a.headers,status:c,rawUrl:e.url,urlParams:e.urlParams});return V(f),a.ok?{success:!0,status:c,message:(o==null?void 0:o.message)||t[e.method],response:o,cause:null}:{success:!1,status:c,message:(o==null?void 0:o.message)||a.statusText||"Request failed",response:o,cause:null}}catch(n){return g({debugs:[`Network error or request failed: ${n}`],name:"MakeRequestError",scheme:"red"}),{success:!1,status:0,message:"Network error or request failed",response:null,cause:n instanceof Error?n.message:String(n)}}}async function Z(e){return b({method:"DELETE",url:e.url,urlParams:e.urlParams,headers:e.headers,body:e.body})}async function G(e){return b({method:"GET",url:e.url,urlParams:e.urlParams,headers:e.headers})}async function W(e){return b({method:"PATCH",url:e.url,urlParams:e.urlParams,headers:e.headers,body:e.body})}async function Y(e){return b({method:"POST",url:e.url,urlParams:e.urlParams,headers:e.headers,body:e.body})}async function K(e){return b({method:"PUT",url:e.url,urlParams:e.urlParams,headers:e.headers,body:e.body})}class Q{constructor(s){l(this,"baseUrl");l(this,"baseHeaders");l(this,"baseToken");l(this,"enableDebug");this.baseUrl=s.baseUrl,this.baseHeaders=s.baseHeaders||void 0,this.baseToken=s.baseToken||void 0,this.enableDebug=s.enableDebug||!1}onDebug(s,t,n){if(this.enableDebug){const r=[];r.push(`Base URL: ${this.baseUrl}`),r.push(`Endpoint: ${s}`),r.push(`Method: ${t}`),n[0]&&r.push(`Headers: ${JSON.stringify(n[0])}`),n[1]&&r.push(`Body: ${JSON.stringify(n[1])}`),g({debugs:r,name:"ARKYN-API-DEBUG",scheme:"yellow"})}}generateHeaders(s,t){let n={};return this.baseToken&&(n={Authorization:`Bearer ${this.baseToken}`}),this.baseHeaders&&(n={...n,...this.baseHeaders}),s&&(n={...n,...s}),t&&(n={...n,Authorization:`Bearer ${t}`}),n}async get(s,t){const n=this.generateHeaders((t==null?void 0:t.headers)||{},t==null?void 0:t.token);return this.onDebug(s,"get",[n]),await G({url:this.baseUrl+s,urlParams:(t==null?void 0:t.urlParams)||{},headers:n})}async post(s,t){const n=this.generateHeaders((t==null?void 0:t.headers)||{},t==null?void 0:t.token),r=t==null?void 0:t.body;return this.onDebug(s,"post",[n,r]),await Y({url:this.baseUrl+s,urlParams:(t==null?void 0:t.urlParams)||{},headers:n,body:r})}async put(s,t){const n=this.generateHeaders((t==null?void 0:t.headers)||{},t==null?void 0:t.token),r=t==null?void 0:t.body;return this.onDebug(s,"put",[n,r]),await K({url:this.baseUrl+s,urlParams:(t==null?void 0:t.urlParams)||{},headers:n,body:r})}async patch(s,t){const n=this.generateHeaders((t==null?void 0:t.headers)||{},t==null?void 0:t.token),r=t==null?void 0:t.body;return this.onDebug(s,"patch",[n,r]),await W({url:this.baseUrl+s,urlParams:(t==null?void 0:t.urlParams)||{},headers:n,body:r})}async delete(s,t){const n=this.generateHeaders((t==null?void 0:t.headers)||{},t==null?void 0:t.token),r=t==null?void 0:t.body;return this.onDebug(s,"delete",[n,r]),await Z({url:this.baseUrl+s,urlParams:(t==null?void 0:t.urlParams)||{},headers:n,body:r})}}async function X(e){let s;const t=await e.arrayBuffer(),n=new TextDecoder().decode(t);try{s=JSON.parse(n)}catch{try{if(n.includes("=")){const a=new URLSearchParams(n);s=Object.fromEntries(a.entries())}else throw new S("Invalid URLSearchParams format")}catch{throw new S("Failed to extract data from request")}}return s}function ss(e,s){var t,n,r;return e!=null&&e.message&&typeof(e==null?void 0:e.message)=="string"?e==null?void 0:e.message:e!=null&&e.error&&typeof(e==null?void 0:e.error)=="string"?e==null?void 0:e.error:(t=e==null?void 0:e.error)!=null&&t.message&&typeof((n=e==null?void 0:e.error)==null?void 0:n.message)=="string"?(r=e==null?void 0:e.error)==null?void 0:r.message:s!=null&&s.statusText&&typeof(s==null?void 0:s.statusText)=="string"?s==null?void 0:s.statusText:"Missing error message"}function es(e){switch(!0){case e instanceof Response:return e;case e instanceof J:return e.toResponse();case e instanceof j:return e.toResponse();case e instanceof _:return e.toResponse();case e instanceof I:return e.toResponse();case e instanceof C:return e.toResponse()}switch(!0){case e instanceof P:return e.toResponse();case e instanceof S:return e.toResponse();case e instanceof B:return e.toResponse();case e instanceof O:return e.toResponse();case e instanceof $:return e.toResponse();case e instanceof k:return e.toResponse();case e instanceof v:return e.toResponse();case e instanceof w:return e.toResponse();case e instanceof N:return e.toResponse()}return new v("Server error",e).toResponse()}async function U([e,s]){const t=await s.safeParseAsync(e);if(t.success===!1){const n=Object.fromEntries(t.error.issues.map(r=>[r.path.join("."),r.message]));return{success:t.success,fieldErrors:n,fields:e}}else return{success:t.success,data:t.data}}function q([e,s]){const t=s.safeParse(e);if(t.success===!1){const n=Object.fromEntries(t.error.issues.map(r=>[r.path.join("."),r.message]));return{success:t.success,fieldErrors:n,fields:e}}else return{success:t.success,data:t.data}}function ts(e,s=""){const t=new URL(e.url);if(s==="")return t.searchParams;const n=Array.from(t.searchParams.entries()).filter(([r])=>r.startsWith(`${s}:`)).map(([r,a])=>[r.replace(`${s}:`,""),a]);return new URLSearchParams(n)}function ns(e){const s="Error validating:",t=e.issues.map(({path:n,message:r})=>`-> ${n.join(".")}: ${r}`);return[s,...t].join(`
5
+ `)}class rs{constructor(s){this.schema=s}isValid(s){return this.schema.safeParse(s).success}safeValidate(s){return this.schema.safeParse(s)}validate(s){try{return this.schema.parse(s)}catch(t){throw new v(ns(t))}}formValidate(s,t){const n=q([s,this.schema]);if(!n.success){const r=Object.keys(n.fieldErrors)[0];throw new N({fields:n.fields,fieldErrors:n.fieldErrors,data:{scrollTo:r},message:t})}return n.data}async formAsyncValidate(s,t){const n=await U([s,this.schema]);if(!n.success){const r=Object.keys(n.fieldErrors)[0];throw new N({fields:n.fields,fieldErrors:n.fieldErrors,data:{scrollTo:r},message:t})}return n.data}}function is(e){if(!(/^\d{5}-\d{3}$/.test(e)||/^\d{8}$/.test(e)))return!1;const t=d.removeNonNumeric(e),n=8,r=/^\d{8}$/.test(t);return t.length===n&&r}function os(e){return e.length!==14}function as(e){const[s]=e;return[...e].every(t=>t===s)}function A(e,s){let t=0;for(let r=0;r<s.length;r++)t+=parseInt(e[r])*s[r];const n=t%11;return n<2?0:11-n}function us(e){return e.slice(12)}function cs(e){if(!e||e.length>18||e.length<14||/\s/.test(e))return!1;const t=d.removeNonNumeric(e);if(os(t)||as(t))return!1;const n=t.slice(0,12),r=A(n,[5,4,3,2,9,8,7,6,5,4,3,2]),a=A(n+r,[6,5,4,3,2,9,8,7,6,5,4,3,2]);return us(t)===`${r}${a}`}function ls(e){return e.length!==11}function hs(e){const[s]=e;return[...e].every(t=>t===s)}function H(e,s){let t=0;for(const r of e)s>1&&(t+=parseInt(r)*s--);const n=t%11;return n<2?0:11-n}function fs(e){return e.slice(9)}function ds(e){if(!e||e.length>14||e.length<11||/\s/.test(e))return!1;const t=d.removeNonNumeric(e);if(ls(t)||hs(t))return!1;const n=H(t,10),r=H(t,11);return fs(t)===`${n}${r}`}function ms(e,s){const t=(s==null?void 0:s.inputFormat)||"brazilianDate",n=(s==null?void 0:s.minYear)||1900,r=(s==null?void 0:s.maxYear)||3e3,a=new d.ValidateDateService;a.validateInputFormat(t);let u,c,o;const f=e.split(/[-/]/).map(Number);if(f.length!==3)return!1;try{switch(t){case"brazilianDate":[u,c,o]=f,a.validateDateParts(o,c,u);break;case"isoDate":[c,u,o]=f,a.validateDateParts(o,c,u);break;case"timestamp":[o,c,u]=f,a.validateDateParts(o,c,u);break}return!(o<n||o>r)}catch{return!1}}function ys(e){return/^[a-zA-Z0-9.!$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e)}function gs(e){return!(e.length===0||e.length>64||e.startsWith(".")||e.endsWith(".")||e.includes("..")||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(e))}function ps(e){return!(e.length===0||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-zA-Z0-9-]+$/.test(e))}function Ts(e){if(e.length===0||e.length>253||e.startsWith(".")||e.endsWith(".")||e.startsWith("-")||e.endsWith("-"))return!1;const s=e.split(".");if(s.length<2)return!1;for(const n of s)if(!ps(n))return!1;const t=s[s.length-1];return!(t.length<2||!/^[a-zA-Z]+$/.test(t))}function bs(e){const s=e.split("@");if(s.length!==2)return!1;const[t,n]=s;return!(!gs(t)||!Ts(n))}function Rs(e){const s=e.split("@");return s.length===2?s[1].toLowerCase():null}const xs=["MX","A","AAAA"];async function Ss(e,s){var t;try{return await((t=D==null?void 0:D.promises)==null?void 0:t.resolve(e,s)),!0}catch{return!1}}async function vs(e){for(const s of xs)if(await Ss(e,s))return!0;return!1}async function Ns(e){if(!e||typeof e!="string")return!1;const s=e.trim();if(!ys(s)||!bs(s))return!1;const t=Rs(s);return t?await vs(t):!1}function Ds(e){if(!e)return!1;const s=e.length>=8,t=/[A-Z]/.test(e),n=/[a-z]/.test(e),r=/\d/.test(e),a=/[!@#$%^&*(),.?":;{}|<>_\-+=~`[\]\\\/]/.test(e);return[s,t,n,r,a].every(u=>u)}function Es(e){for(const s of L.countries){const t=s.code,n=s.prefix?`-${s.prefix}`:"",r=s.mask.replace(/[^_]/g,"").length;if(s.iso==="BR"){if(new RegExp(`^\\${t} \\d{2}9?\\d{8}$`).test(e))return!0;continue}if(new RegExp(`^\\${t}${n} \\d{${r}}$`).test(e))return!0}return!1}function Ps(e){if(!e||!/^[0-9a-zA-Z.-]+$/.test(e))return!1;const t=e.replace(/[^a-zA-Z0-9]/g,"");return t.length<7||t.length>9?!1:/^[0-9]{7,8}[0-9Xx]?$/.test(t)}i.ApiService=Q,i.BadGateway=P,i.BadRequest=S,i.Conflict=B,i.Created=j,i.DebugService=x,i.Forbidden=O,i.Found=J,i.LogService=E,i.NoContent=C,i.NotFound=$,i.NotImplemented=k,i.SchemaValidator=rs,i.ServerError=v,i.Success=I,i.Unauthorized=w,i.UnprocessableEntity=N,i.Updated=_,i.decodeRequestBody=X,i.decodeRequestErrorMessage=ss,i.errorHandler=es,i.flushDebugLogs=g,i.formAsyncParse=U,i.formParse=q,i.getScopedParams=ts,i.validateCep=is,i.validateCnpj=cs,i.validateCpf=ds,i.validateDate=ms,i.validateEmail=Ns,i.validatePassword=Ds,i.validatePhone=Es,i.validateRg=Ps,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});
@@ -13,25 +13,28 @@ type ConfigProps = {
13
13
  /**
14
14
  * Sends a request to the inbox flow API with the provided configuration.
15
15
  *
16
- * @param config - The configuration object for the request.
17
- * @param config.rawUrl - The raw URL of the request.
18
- * @param config.status - The HTTP status code associated with the request.
19
- * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", or "PATCH".
20
- * @param config.token - The authentication token for the request.
21
- * @param config.elapsedTime - The elapsed time for the request in milliseconds.
22
- * @param config.requestHeaders - The headers sent with the request.
23
- * @param config.requestBody - The body of the request, if applicable.
24
- * @param config.queryParams - The query parameters for the request.
25
- * @param config.responseHeaders - The headers received in the response.
26
- * @param config.responseBody - The body of the response received.
27
- *
28
- * @remarks
29
- * - This function retrieves the inbox flow configuration using `InboxFlowService.getInboxConfig()`.
16
+ * - This function retrieves the inbox flow configuration using `LogService.getConfig()`.
30
17
  * - If the configuration is not available, the function will return early without performing any action.
31
18
  * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
32
19
  * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
33
20
  * - If an error occurs during the request, it will be logged using the `httpDebug` service.
34
21
  *
22
+ * @param {ConfigProps} config - The configuration object for the request.
23
+ * @param {string} config.rawUrl - The raw URL of the request.
24
+ * @param {number} config.status - The HTTP status code associated with the request.
25
+ * @param {"GET" | "POST" | "PUT" | "DELETE" | "PATCH"} config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", or "PATCH".
26
+ * @param {string | null} config.token - The authentication token for the request.
27
+ * @param {number} config.elapsedTime - The elapsed time for the request in milliseconds.
28
+ * @param {Record<string, string>} config.requestHeaders - The headers sent with the request.
29
+ * @param {Record<string, string>} config.requestBody - The body of the request, if applicable.
30
+ * @param {Record<string, string>} config.queryParams - The query parameters for the request.
31
+ * @param {Record<string, string>} config.responseHeaders - The headers received in the response.
32
+ * @param {Record<string, string>} config.responseBody - The body of the response received.
33
+ *
34
+ * @remarks
35
+ *
36
+ * @returns {Promise<void>} A promise that resolves when the request is complete.
37
+ *
35
38
  * @example
36
39
  * ```typescript
37
40
  * const config = {
@@ -39,7 +42,7 @@ type ConfigProps = {
39
42
  * status: 200,
40
43
  * method: "GET",
41
44
  * token: "auth-token-123",
42
- * elapsedTime: "150ms",
45
+ * elapsedTime: 150,
43
46
  * requestHeaders: { "Accept": "application/json", "Authorization": "Bearer token123" },
44
47
  * requestBody: {},
45
48
  * queryParams: { "page": "1", "limit": "10" },
@@ -47,9 +50,9 @@ type ConfigProps = {
47
50
  * responseBody: { "data": "example response" }
48
51
  * };
49
52
  *
50
- * await arkynLogRequest(config);
53
+ * await logRequest(config);
51
54
  * ```
52
55
  */
53
- declare function arkynLogRequest(config: ConfigProps): Promise<void>;
54
- export { arkynLogRequest };
55
- //# sourceMappingURL=arkynLogRequest.d.ts.map
56
+ declare function logRequest(config: ConfigProps): Promise<void>;
57
+ export { logRequest };
58
+ //# sourceMappingURL=_logRequest.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"arkynLogRequest.d.ts","sourceRoot":"","sources":["../../src/api/arkynLogRequest.ts"],"names":[],"mappings":"AAGA,KAAK,WAAW,GAAG;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,CAAC;IACpD,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,iBAAe,eAAe,CAAC,MAAM,EAAE,WAAW,iBAyDjD;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
1
+ {"version":3,"file":"_logRequest.d.ts","sourceRoot":"","sources":["../../../src/http/api/_logRequest.ts"],"names":[],"mappings":"AAGA,KAAK,WAAW,GAAG;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,CAAC;IACpD,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AAEH,iBAAe,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAwD5D;AAED,OAAO,EAAE,UAAU,EAAE,CAAC"}
@@ -1,27 +1,30 @@
1
- import { ArkynLogService } from "../services/arkynLogService";
2
- import { flushDebugLogs } from "../services/flushDebugLogs";
1
+ import { flushDebugLogs } from "../..";
2
+ import { LogService } from "../../services/logService";
3
3
  /**
4
4
  * Sends a request to the inbox flow API with the provided configuration.
5
5
  *
6
- * @param config - The configuration object for the request.
7
- * @param config.rawUrl - The raw URL of the request.
8
- * @param config.status - The HTTP status code associated with the request.
9
- * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", or "PATCH".
10
- * @param config.token - The authentication token for the request.
11
- * @param config.elapsedTime - The elapsed time for the request in milliseconds.
12
- * @param config.requestHeaders - The headers sent with the request.
13
- * @param config.requestBody - The body of the request, if applicable.
14
- * @param config.queryParams - The query parameters for the request.
15
- * @param config.responseHeaders - The headers received in the response.
16
- * @param config.responseBody - The body of the response received.
17
- *
18
- * @remarks
19
- * - This function retrieves the inbox flow configuration using `InboxFlowService.getInboxConfig()`.
6
+ * - This function retrieves the inbox flow configuration using `LogService.getConfig()`.
20
7
  * - If the configuration is not available, the function will return early without performing any action.
21
8
  * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
22
9
  * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
23
10
  * - If an error occurs during the request, it will be logged using the `httpDebug` service.
24
11
  *
12
+ * @param {ConfigProps} config - The configuration object for the request.
13
+ * @param {string} config.rawUrl - The raw URL of the request.
14
+ * @param {number} config.status - The HTTP status code associated with the request.
15
+ * @param {"GET" | "POST" | "PUT" | "DELETE" | "PATCH"} config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", or "PATCH".
16
+ * @param {string | null} config.token - The authentication token for the request.
17
+ * @param {number} config.elapsedTime - The elapsed time for the request in milliseconds.
18
+ * @param {Record<string, string>} config.requestHeaders - The headers sent with the request.
19
+ * @param {Record<string, string>} config.requestBody - The body of the request, if applicable.
20
+ * @param {Record<string, string>} config.queryParams - The query parameters for the request.
21
+ * @param {Record<string, string>} config.responseHeaders - The headers received in the response.
22
+ * @param {Record<string, string>} config.responseBody - The body of the response received.
23
+ *
24
+ * @remarks
25
+ *
26
+ * @returns {Promise<void>} A promise that resolves when the request is complete.
27
+ *
25
28
  * @example
26
29
  * ```typescript
27
30
  * const config = {
@@ -29,7 +32,7 @@ import { flushDebugLogs } from "../services/flushDebugLogs";
29
32
  * status: 200,
30
33
  * method: "GET",
31
34
  * token: "auth-token-123",
32
- * elapsedTime: "150ms",
35
+ * elapsedTime: 150,
33
36
  * requestHeaders: { "Accept": "application/json", "Authorization": "Bearer token123" },
34
37
  * requestBody: {},
35
38
  * queryParams: { "page": "1", "limit": "10" },
@@ -37,11 +40,11 @@ import { flushDebugLogs } from "../services/flushDebugLogs";
37
40
  * responseBody: { "data": "example response" }
38
41
  * };
39
42
  *
40
- * await arkynLogRequest(config);
43
+ * await logRequest(config);
41
44
  * ```
42
45
  */
43
- async function arkynLogRequest(config) {
44
- const arkynService = ArkynLogService.getArkynConfig();
46
+ async function logRequest(config) {
47
+ const arkynService = LogService.getConfig();
45
48
  if (!arkynService)
46
49
  return;
47
50
  const { userToken, apiUrl, trafficSourceId } = arkynService;
@@ -68,21 +71,18 @@ async function arkynLogRequest(config) {
68
71
  responseHeaders: JSON.stringify(responseHeaders),
69
72
  responseBody: JSON.stringify(responseBody),
70
73
  });
71
- await fetch(apiUrl, {
72
- method: "POST",
73
- body,
74
- headers: {
75
- "Content-Type": "application/json",
76
- Authorization: `Bearer ${userToken}`,
77
- },
78
- });
74
+ const headers = {
75
+ "Content-Type": "application/json",
76
+ Authorization: `Bearer ${userToken}`,
77
+ };
78
+ await fetch(apiUrl, { method: "POST", body, headers });
79
79
  }
80
80
  catch (err) {
81
81
  flushDebugLogs({
82
82
  debugs: [`Error sending request: ${err}`],
83
- name: "ARKYN_LOG_ERROR",
83
+ name: "LogError",
84
84
  scheme: "red",
85
85
  });
86
86
  }
87
87
  }
88
- export { arkynLogRequest };
88
+ export { logRequest };
@@ -0,0 +1,61 @@
1
+ type InputProps = {
2
+ url: string;
3
+ method: "POST" | "PUT" | "DELETE" | "PATCH" | "GET";
4
+ urlParams?: Record<string, string>;
5
+ headers?: HeadersInit;
6
+ body?: any;
7
+ };
8
+ type ApiSuccessResponse<T = any> = {
9
+ success: true;
10
+ status: number;
11
+ message: string;
12
+ response: T;
13
+ cause: null;
14
+ };
15
+ type ApiFailedResponse = {
16
+ success: false;
17
+ status: number;
18
+ message: string;
19
+ response: any;
20
+ cause: string | Error | null;
21
+ };
22
+ type ApiResponseDTO<T = any> = ApiSuccessResponse<T> | ApiFailedResponse;
23
+ /**
24
+ * Makes an HTTP request using the Fetch API and returns a standardized response.
25
+ *
26
+ * @template {any} T - The expected type of the response data.
27
+ *
28
+ * @param {"POST" | "PUT" | "DELETE" | "PATCH" | "GET"} method - The HTTP method to use for the request. Supported methods are:
29
+ * - "POST": Create a new resource.
30
+ * - "PUT": Update an existing resource.
31
+ * - "DELETE": Remove a resource.
32
+ * - "PATCH": Partially update a resource.
33
+ * - "GET": Retrieve a resource.
34
+ * @param {string} url - The URL to which the request is sent.
35
+ * @param {HeadersInit} headers - Optional headers to include in the request. Defaults to an empty object.
36
+ * @param {any} body - Optional body to include in the request. Should be serializable to JSON.
37
+ *
38
+ * @returns {ApiResponseDTO<T>} A promise that resolves to an `ApiResponseDTO<T>` object containing:
39
+ * - `success`: A boolean indicating whether the request was successful.
40
+ * - `status`: The HTTP status code of the response.
41
+ * - `message`: A message describing the result of the request.
42
+ * - `response`: The parsed JSON response data, or `null` if parsing fails.
43
+ * - `cause`: Additional error information, if applicable.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * import { makeRequest } from "./makeRequest";
48
+ *
49
+ * async function fetchData() {
50
+ * const response = await makeRequest("GET", "https://api.example.com/data");
51
+ * if (response.success) {
52
+ * console.log("Data:", response.response);
53
+ * } else {
54
+ * console.error("Error:", response.message);
55
+ * }
56
+ * }
57
+ * ```
58
+ */
59
+ declare function makeRequest<T = any>(input: InputProps): Promise<ApiResponseDTO<T>>;
60
+ export { makeRequest, type ApiResponseDTO };
61
+ //# sourceMappingURL=_makeRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_makeRequest.d.ts","sourceRoot":"","sources":["../../../src/http/api/_makeRequest.ts"],"names":[],"mappings":"AAIA,KAAK,UAAU,GAAG;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,GAAG,KAAK,CAAC;IACpD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ,CAAC;AAEF,KAAK,kBAAkB,CAAC,CAAC,GAAG,GAAG,IAAI;IACjC,OAAO,EAAE,IAAI,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,CAAC,CAAC;IACZ,KAAK,EAAE,IAAI,CAAC;CACb,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,OAAO,EAAE,KAAK,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,GAAG,CAAC;IACd,KAAK,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CAC9B,CAAC;AAEF,KAAK,cAAc,CAAC,CAAC,GAAG,GAAG,IAAI,kBAAkB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,iBAAe,WAAW,CAAC,CAAC,GAAG,GAAG,EAChC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAoF5B;AAED,OAAO,EAAE,WAAW,EAAE,KAAK,cAAc,EAAE,CAAC"}
@@ -1,20 +1,22 @@
1
- import { ArkynLogRequestMapper } from "../mapper/arkynLogRequestMapper";
2
- import { flushDebugLogs } from "../services/flushDebugLogs";
3
- import { arkynLogRequest } from "./arkynLogRequest";
1
+ import { flushDebugLogs } from "../..";
2
+ import { LogMapperService } from "../../services/logMapperService";
3
+ import { logRequest } from "./_logRequest";
4
4
  /**
5
5
  * Makes an HTTP request using the Fetch API and returns a standardized response.
6
6
  *
7
- * @template T - The expected type of the response data.
8
- * @param method - The HTTP method to use for the request. Supported methods are:
7
+ * @template {any} T - The expected type of the response data.
8
+ *
9
+ * @param {"POST" | "PUT" | "DELETE" | "PATCH" | "GET"} method - The HTTP method to use for the request. Supported methods are:
9
10
  * - "POST": Create a new resource.
10
11
  * - "PUT": Update an existing resource.
11
12
  * - "DELETE": Remove a resource.
12
13
  * - "PATCH": Partially update a resource.
13
14
  * - "GET": Retrieve a resource.
14
- * @param url - The URL to which the request is sent.
15
- * @param headers - Optional headers to include in the request. Defaults to an empty object.
16
- * @param body - Optional body to include in the request. Should be serializable to JSON.
17
- * @returns A promise that resolves to an `ApiResponseDTO<T>` object containing:
15
+ * @param {string} url - The URL to which the request is sent.
16
+ * @param {HeadersInit} headers - Optional headers to include in the request. Defaults to an empty object.
17
+ * @param {any} body - Optional body to include in the request. Should be serializable to JSON.
18
+ *
19
+ * @returns {ApiResponseDTO<T>} A promise that resolves to an `ApiResponseDTO<T>` object containing:
18
20
  * - `success`: A boolean indicating whether the request was successful.
19
21
  * - `status`: The HTTP status code of the response.
20
22
  * - `message`: A message describing the result of the request.
@@ -35,7 +37,13 @@ import { arkynLogRequest } from "./arkynLogRequest";
35
37
  * }
36
38
  * ```
37
39
  */
38
- async function makeRequest(method, url, rawHeaders = {}, body) {
40
+ async function makeRequest(input) {
41
+ let url = input.url;
42
+ if (input.urlParams) {
43
+ Object.entries(input.urlParams).forEach(([key, value]) => {
44
+ url = url.replaceAll(`:${key}`, value);
45
+ });
46
+ }
39
47
  const successMessage = {
40
48
  POST: "Resource created successfully",
41
49
  PUT: "Resource updated successfully",
@@ -45,11 +53,11 @@ async function makeRequest(method, url, rawHeaders = {}, body) {
45
53
  };
46
54
  try {
47
55
  const startTime = performance.now();
48
- const headers = { ...rawHeaders, "Content-Type": "application/json" };
56
+ const headers = { ...input.headers, "Content-Type": "application/json" };
49
57
  const response = await fetch(url, {
50
- method,
51
58
  headers,
52
- body: body ? JSON.stringify(body) : undefined,
59
+ method: input.method,
60
+ body: input.body ? JSON.stringify(input.body) : undefined,
53
61
  });
54
62
  const elapsedTime = performance.now() - startTime;
55
63
  const status = response.status;
@@ -60,18 +68,19 @@ async function makeRequest(method, url, rawHeaders = {}, body) {
60
68
  catch {
61
69
  data = null;
62
70
  }
63
- const logData = ArkynLogRequestMapper.handle({
71
+ const logData = LogMapperService.handle({
64
72
  elapsedTime,
65
- method,
73
+ method: input.method,
66
74
  queryParams: new URL(url).searchParams,
67
75
  requestHeaders: headers,
68
- requestBody: body,
76
+ requestBody: input.body,
69
77
  responseBody: data,
70
78
  responseHeaders: response.headers,
71
79
  status,
72
- url,
80
+ rawUrl: input.url,
81
+ urlParams: input.urlParams,
73
82
  });
74
- arkynLogRequest(logData);
83
+ logRequest(logData);
75
84
  if (!response.ok) {
76
85
  return {
77
86
  success: false,
@@ -84,7 +93,7 @@ async function makeRequest(method, url, rawHeaders = {}, body) {
84
93
  return {
85
94
  success: true,
86
95
  status,
87
- message: data?.message || successMessage[method],
96
+ message: data?.message || successMessage[input.method],
88
97
  response: data,
89
98
  cause: null,
90
99
  };
@@ -92,7 +101,7 @@ async function makeRequest(method, url, rawHeaders = {}, body) {
92
101
  catch (err) {
93
102
  flushDebugLogs({
94
103
  debugs: [`Network error or request failed: ${err}`],
95
- name: "ARKYN_MAKE_REQUEST_ERROR",
104
+ name: "MakeRequestError",
96
105
  scheme: "red",
97
106
  });
98
107
  return {
@@ -0,0 +1,17 @@
1
+ import { type ApiResponseDTO } from "./_makeRequest";
2
+ type InputProps = {
3
+ url: string;
4
+ urlParams?: Record<string, string>;
5
+ headers?: HeadersInit;
6
+ body?: any;
7
+ };
8
+ /**
9
+ * Sends a DELETE request to the specified URL with optional headers and body.
10
+ *
11
+ * @template T - The expected type of the response data.
12
+ * @param {InputProps} input - The options for the DELETE request, including URL, URL parameters, headers, and body.
13
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
14
+ */
15
+ declare function deleteRequest<T = any>(input: InputProps): Promise<ApiResponseDTO<T>>;
16
+ export { deleteRequest };
17
+ //# sourceMappingURL=deleteRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deleteRequest.d.ts","sourceRoot":"","sources":["../../../src/http/api/deleteRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAElE,KAAK,UAAU,GAAG;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ,CAAC;AAEF;;;;;;GAMG;AAEH,iBAAe,aAAa,CAAC,CAAC,GAAG,GAAG,EAClC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAQ5B;AAED,OAAO,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { makeRequest } from "./_makeRequest";
2
+ /**
3
+ * Sends a DELETE request to the specified URL with optional headers and body.
4
+ *
5
+ * @template T - The expected type of the response data.
6
+ * @param {InputProps} input - The options for the DELETE request, including URL, URL parameters, headers, and body.
7
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
8
+ */
9
+ async function deleteRequest(input) {
10
+ return makeRequest({
11
+ method: "DELETE",
12
+ url: input.url,
13
+ urlParams: input.urlParams,
14
+ headers: input.headers,
15
+ body: input.body,
16
+ });
17
+ }
18
+ export { deleteRequest };
@@ -0,0 +1,16 @@
1
+ import { type ApiResponseDTO } from "./_makeRequest";
2
+ type InputProps = {
3
+ url: string;
4
+ urlParams?: Record<string, string>;
5
+ headers?: HeadersInit;
6
+ };
7
+ /**
8
+ * Sends a GET request to the specified URL with optional headers.
9
+ *
10
+ * @template T - The expected type of the response data.
11
+ * @param {InputProps} input - The options for the GET request, including URL, URL parameters, and headers.
12
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
13
+ */
14
+ declare function getRequest<T = any>(input: InputProps): Promise<ApiResponseDTO<T>>;
15
+ export { getRequest };
16
+ //# sourceMappingURL=getRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getRequest.d.ts","sourceRoot":"","sources":["../../../src/http/api/getRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAElE,KAAK,UAAU,GAAG;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,WAAW,CAAC;CACvB,CAAC;AAEF;;;;;;GAMG;AAEH,iBAAe,UAAU,CAAC,CAAC,GAAG,GAAG,EAC/B,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAO5B;AAED,OAAO,EAAE,UAAU,EAAE,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { makeRequest } from "./_makeRequest";
2
+ /**
3
+ * Sends a GET request to the specified URL with optional headers.
4
+ *
5
+ * @template T - The expected type of the response data.
6
+ * @param {InputProps} input - The options for the GET request, including URL, URL parameters, and headers.
7
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
8
+ */
9
+ async function getRequest(input) {
10
+ return makeRequest({
11
+ method: "GET",
12
+ url: input.url,
13
+ urlParams: input.urlParams,
14
+ headers: input.headers,
15
+ });
16
+ }
17
+ export { getRequest };
@@ -0,0 +1,17 @@
1
+ import { type ApiResponseDTO } from "./_makeRequest";
2
+ type InputProps = {
3
+ url: string;
4
+ urlParams?: Record<string, string>;
5
+ headers?: HeadersInit;
6
+ body?: any;
7
+ };
8
+ /**
9
+ * Sends a PATCH request to the specified URL with optional headers and body.
10
+ *
11
+ * @template T - The expected type of the response data.
12
+ * @param {InputProps} input - The options for the PATCH request, including URL, URL parameters, headers, and body.
13
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
14
+ */
15
+ declare function patchRequest<T = any>(input: InputProps): Promise<ApiResponseDTO<T>>;
16
+ export { patchRequest };
17
+ //# sourceMappingURL=patchRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patchRequest.d.ts","sourceRoot":"","sources":["../../../src/http/api/patchRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAElE,KAAK,UAAU,GAAG;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ,CAAC;AAEF;;;;;;GAMG;AAEH,iBAAe,YAAY,CAAC,CAAC,GAAG,GAAG,EACjC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAQ5B;AAED,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { makeRequest } from "./_makeRequest";
2
+ /**
3
+ * Sends a PATCH request to the specified URL with optional headers and body.
4
+ *
5
+ * @template T - The expected type of the response data.
6
+ * @param {InputProps} input - The options for the PATCH request, including URL, URL parameters, headers, and body.
7
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
8
+ */
9
+ async function patchRequest(input) {
10
+ return makeRequest({
11
+ method: "PATCH",
12
+ url: input.url,
13
+ urlParams: input.urlParams,
14
+ headers: input.headers,
15
+ body: input.body,
16
+ });
17
+ }
18
+ export { patchRequest };
@@ -0,0 +1,17 @@
1
+ import { type ApiResponseDTO } from "./_makeRequest";
2
+ type InputProps = {
3
+ url: string;
4
+ urlParams?: Record<string, string>;
5
+ headers?: HeadersInit;
6
+ body?: any;
7
+ };
8
+ /**
9
+ * Sends a POST request to the specified URL with optional headers and body.
10
+ *
11
+ * @template T - The expected type of the response data.
12
+ * @param {InputProps} input - The options for the POST request, including URL, URL parameters, headers, and body.
13
+ * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
14
+ */
15
+ declare function postRequest<T = any>(input: InputProps): Promise<ApiResponseDTO<T>>;
16
+ export { postRequest };
17
+ //# sourceMappingURL=postRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postRequest.d.ts","sourceRoot":"","sources":["../../../src/http/api/postRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAElE,KAAK,UAAU,GAAG;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ,CAAC;AAEF;;;;;;GAMG;AAEH,iBAAe,WAAW,CAAC,CAAC,GAAG,GAAG,EAChC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAQ5B;AAED,OAAO,EAAE,WAAW,EAAE,CAAC"}