@catbee/utils 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -4
- package/build/esm/config.d.ts +1 -5
- package/build/esm/config.js +6 -10
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +20 -19
- package/build/esm/index.js +20 -19
- package/build/esm/index.js.map +1 -1
- package/build/esm/types/api-response.d.ts +2 -2
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/utils/array.utils.d.ts +1 -1
- package/build/esm/utils/array.utils.js +17 -27
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +1 -5
- package/build/esm/utils/async.utils.js +17 -20
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +2 -2
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +8 -8
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.d.ts +2 -2
- package/build/esm/utils/crypto.utils.js +37 -45
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +2 -18
- package/build/esm/utils/decorators.utils.js +31 -31
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.d.ts +4 -4
- package/build/esm/utils/dir.utils.js +18 -20
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.js +22 -26
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.d.ts +1 -1
- package/build/esm/utils/exception.utils.js +26 -29
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.d.ts +3 -3
- package/build/esm/utils/fs.utils.js +19 -23
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +8 -8
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +13 -4
- package/build/esm/utils/logger.utils.js +16 -18
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +15 -26
- package/build/esm/utils/middleware.utils.js +80 -59
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.js +16 -27
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +2 -2
- package/build/esm/utils/response.utils.js +11 -11
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +17 -17
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +20 -22
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.js +11 -15
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +1 -5
- package/build/esnext/config.js +6 -10
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +20 -19
- package/build/esnext/index.js +20 -19
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/types/api-response.d.ts +2 -2
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/utils/array.utils.d.ts +1 -1
- package/build/esnext/utils/array.utils.js +23 -31
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +1 -5
- package/build/esnext/utils/async.utils.js +22 -22
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +3 -3
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +10 -10
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.d.ts +2 -2
- package/build/esnext/utils/crypto.utils.js +37 -47
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +2 -18
- package/build/esnext/utils/decorators.utils.js +33 -33
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.d.ts +4 -4
- package/build/esnext/utils/dir.utils.js +22 -24
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.js +24 -26
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.d.ts +1 -1
- package/build/esnext/utils/exception.utils.js +26 -29
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.d.ts +3 -3
- package/build/esnext/utils/fs.utils.js +21 -25
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +8 -8
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +13 -4
- package/build/esnext/utils/logger.utils.js +16 -18
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +15 -26
- package/build/esnext/utils/middleware.utils.js +78 -59
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.js +17 -26
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +2 -2
- package/build/esnext/utils/response.utils.js +11 -11
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +17 -17
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +21 -23
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.js +14 -16
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +1 -5
- package/build/src/config.js +5 -9
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +20 -19
- package/build/src/index.js +1 -0
- package/build/src/index.js.map +1 -1
- package/build/src/types/api-response.d.ts +2 -2
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/utils/array.utils.d.ts +1 -1
- package/build/src/utils/array.utils.js +22 -30
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +1 -5
- package/build/src/utils/async.utils.js +22 -22
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +2 -2
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +9 -9
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.d.ts +2 -2
- package/build/src/utils/crypto.utils.js +35 -45
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +2 -18
- package/build/src/utils/decorators.utils.js +32 -32
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.d.ts +4 -4
- package/build/src/utils/dir.utils.js +16 -18
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.js +22 -24
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.d.ts +1 -1
- package/build/src/utils/exception.utils.js +23 -26
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.d.ts +3 -3
- package/build/src/utils/fs.utils.js +15 -19
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +7 -7
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +13 -4
- package/build/src/utils/logger.utils.js +13 -15
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +15 -26
- package/build/src/utils/middleware.utils.js +72 -52
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.js +17 -26
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +2 -2
- package/build/src/utils/response.utils.js +9 -9
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +17 -17
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +20 -22
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.js +14 -16
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exception.utils.js","sourceRoot":"","sources":["../../../src/utils/exception.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD;;;GAGG;AACH,MAAM,OAAO,SAAU,SAAQ,aAAa;IAC1C;;;;OAIG;IACH,YAAY,MAAc,EAAE,OAAe;QACzC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,4BAA6B,SAAQ,aAAa;IAC7D;;OAEG;IACH,YAAY,UAAkB,uBAAuB;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,qBAAqB,CAAC;IACtD,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,qBAAsB,SAAQ,aAAa;IACtD;;OAEG;IACH,YAAY,UAAkB,cAAc;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,YAAY,CAAC;IAC7C,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,mBAAoB,SAAQ,aAAa;IACpD;;OAEG;IACH,YAAY,UAAkB,aAAa;QACzC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,WAAW,CAAC;IAC5C,CAAC;CACF;AAED;;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;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IAED,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IAED,OAAO,wBAAwB,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAU;IAEV,OAAO,KAAK,EAAE,GAAG,IAAmB,EAAE,EAAE;QACtC,IAAI,CAAC;YACH,OAAO,MAAM,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,MAAM,KAAK,CAAC;YACd,CAAC;YAED,0DAA0D;YAC1D,SAAS,EAAE,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YAErD,sDAAsD;YACtD,IAAI,MAAM,GAAG,eAAe,CAAC,qBAAqB,CAAC;YACnD,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;gBAC7D,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;YACxB,CAAC;YAED,gCAAgC;YAChC,MAAM,eAAe,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACxD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { HttpStatusCodes } from \"./http-status-codes\";\nimport { getLogger } from \"./logger.utils\";\nimport { ErrorResponse } from \"./response.utils\";\n\n/**\n * Generic HTTP error class used for custom exceptions with any status code.\n * Inherit this when you need to throw errors dynamically at runtime.\n */\nexport class HttpError extends ErrorResponse {\n /**\n * Creates a new HTTP error instance.\n * @param status - A valid HTTP status code (e.g., 400, 500).\n * @param message - The error message to return to the client.\n */\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\n/**\n * Represents a 500 Internal Server Error.\n * Use this for unexpected backend errors that are not caused by the client.\n */\nexport class InternalServerErrorException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Internal server error\".\n */\n constructor(message: string = \"Internal server error\") {\n super(message);\n this.status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n }\n}\n\n/**\n * Represents a 401 Unauthorized Error.\n * Indicates that authentication is required and has failed or not been provided.\n */\nexport class UnauthorizedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unauthorized\".\n */\n constructor(message: string = \"Unauthorized\") {\n super(message);\n this.status = HttpStatusCodes.UNAUTHORIZED;\n }\n}\n\n/**\n * Represents a 400 Bad Request Error.\n * Indicates that the client has sent invalid data (e.g., malformed request body).\n */\nexport class BadRequestException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad request\".\n */\n constructor(message: string = \"Bad request\") {\n super(message);\n this.status = HttpStatusCodes.BAD_REQUEST;\n }\n}\n\n/**\n * Represents a 404 Not Found Error.\n * Used when a requested resource (e.g., user, file) could not be located.\n */\nexport class NotFoundException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Resource not found\".\n */\n constructor(message: string = \"Resource not found\") {\n super(message);\n this.status = HttpStatusCodes.NOT_FOUND;\n }\n}\n\n/**\n * Represents a 403 Forbidden Error.\n * Indicates that the client is authenticated but not allowed to access the resource.\n */\nexport class ForbiddenException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Forbidden\".\n */\n constructor(message: string = \"Forbidden\") {\n super(message);\n this.status = HttpStatusCodes.FORBIDDEN;\n }\n}\n\n/**\n * Represents a 409 Conflict Error.\n * Commonly used when a resource already exists or a versioning conflict occurs.\n */\nexport class ConflictException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Conflict\".\n */\n constructor(message: string = \"Conflict\") {\n super(message);\n this.status = HttpStatusCodes.CONFLICT;\n }\n}\n\n/**\n * Represents a 502 Bad Gateway Error.\n * Used when the server receives an invalid response from an upstream server.\n */\nexport class BadGatewayException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad Gateway\".\n */\n constructor(message: string = \"Bad Gateway\") {\n super(message);\n this.status = HttpStatusCodes.BAD_GATEWAY;\n }\n}\n\n/**\n * Represents a 429 Too Many Requests Error.\n * Returned when the client has hit a rate limit.\n */\nexport class TooManyRequestsException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Too many requests\".\n */\n constructor(message: string = \"Too many requests\") {\n super(message);\n this.status = HttpStatusCodes.TOO_MANY_REQUESTS;\n }\n}\n\n/**\n * Represents a 503 Service Unavailable Error.\n * Indicates that the server is temporarily unavailable (e.g., for maintenance).\n */\nexport class ServiceUnavailableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Service Unavailable\".\n */\n constructor(message: string = \"Service Unavailable\") {\n super(message);\n this.status = HttpStatusCodes.SERVICE_UNAVAILABLE;\n }\n}\n\n/**\n * Represents a 504 Gateway Timeout Error.\n * Returned when the server acting as a gateway times out waiting for a response.\n */\nexport class GatewayTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Gateway Timeout\".\n */\n constructor(message: string = \"Gateway Timeout\") {\n super(message);\n this.status = HttpStatusCodes.GATEWAY_TIMEOUT;\n }\n}\n\n/**\n * Represents a 422 Unprocessable Entity Error.\n * Used when the server understands the content type but cannot process the contained instructions.\n */\nexport class UnprocessableEntityException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unprocessable Entity\".\n * @param details - Optional validation details or additional error context.\n */\n constructor(\n message: string = \"Unprocessable Entity\",\n public details?: Record<string, any>,\n ) {\n super(message);\n this.status = HttpStatusCodes.UNPROCESSABLE_ENTITY;\n }\n}\n\n/**\n * Represents a 405 Method Not Allowed Error.\n * Used when the request method is not supported for the requested resource.\n */\nexport class MethodNotAllowedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Method Not Allowed\".\n * @param allowedMethods - Optional array of allowed HTTP methods.\n */\n constructor(\n message: string = \"Method Not Allowed\",\n public allowedMethods?: string[],\n ) {\n super(message);\n this.status = HttpStatusCodes.METHOD_NOT_ALLOWED;\n }\n}\n\n/**\n * Represents a 406 Not Acceptable Error.\n * Used when the server cannot produce a response matching the client's accepted content types.\n */\nexport class NotAcceptableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Not Acceptable\".\n */\n constructor(message: string = \"Not Acceptable\") {\n super(message);\n this.status = HttpStatusCodes.NOT_ACCEPTABLE;\n }\n}\n\n/**\n * Represents a 408 Request Timeout Error.\n * Used when the server times out waiting for the client to send a request.\n */\nexport class RequestTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Request Timeout\".\n */\n constructor(message: string = \"Request Timeout\") {\n super(message);\n this.status = HttpStatusCodes.REQUEST_TIMEOUT;\n }\n}\n\n/**\n * Represents a 415 Unsupported Media Type Error.\n * Used when the request's Content-Type is not supported.\n */\nexport class UnsupportedMediaTypeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unsupported Media Type\".\n */\n constructor(message: string = \"Unsupported Media Type\") {\n super(message);\n this.status = HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;\n }\n}\n\n/**\n * Represents a 413 Payload Too Large Error.\n * Used when the request body exceeds server limits.\n */\nexport class PayloadTooLargeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Payload Too Large\".\n */\n constructor(message: string = \"Payload Too Large\") {\n super(message);\n this.status = HttpStatusCodes.PAYLOAD_TOO_LARGE;\n }\n}\n\n/**\n * Represents a 507 Insufficient Storage Error.\n * Used when the server has insufficient storage to complete the request.\n */\nexport class InsufficientStorageException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Insufficient Storage\".\n */\n constructor(message: string = \"Insufficient Storage\") {\n super(message);\n this.status = HttpStatusCodes.INSUFFICIENT_STORAGE;\n }\n}\n\n/**\n * Checks if an error is an instance of HttpError or its subclasses.\n *\n * @param error - The error to check.\n * @returns True if the error is an HttpError, false otherwise.\n */\nexport function isHttpError(error: unknown): error is ErrorResponse {\n return error instanceof ErrorResponse;\n}\n\n/**\n * Creates an HTTP error with the specified status code and message.\n * Factory function for creating appropriate HTTP error instances.\n *\n * @param status - HTTP status code.\n * @param message - Optional custom error message.\n * @returns An instance of the appropriate HTTP error class.\n */\nexport function createHttpError(\n status: number,\n message?: string,\n): ErrorResponse {\n switch (status) {\n case HttpStatusCodes.BAD_REQUEST:\n return new BadRequestException(message);\n case HttpStatusCodes.UNAUTHORIZED:\n return new UnauthorizedException(message);\n case HttpStatusCodes.FORBIDDEN:\n return new ForbiddenException(message);\n case HttpStatusCodes.NOT_FOUND:\n return new NotFoundException(message);\n case HttpStatusCodes.METHOD_NOT_ALLOWED:\n return new MethodNotAllowedException(message);\n case HttpStatusCodes.NOT_ACCEPTABLE:\n return new NotAcceptableException(message);\n case HttpStatusCodes.REQUEST_TIMEOUT:\n return new RequestTimeoutException(message);\n case HttpStatusCodes.CONFLICT:\n return new ConflictException(message);\n case HttpStatusCodes.GONE:\n return new HttpError(HttpStatusCodes.GONE, message || \"Gone\");\n case HttpStatusCodes.PAYLOAD_TOO_LARGE:\n return new PayloadTooLargeException(message);\n case HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:\n return new UnsupportedMediaTypeException(message);\n case HttpStatusCodes.UNPROCESSABLE_ENTITY:\n return new UnprocessableEntityException(message);\n case HttpStatusCodes.TOO_MANY_REQUESTS:\n return new TooManyRequestsException(message);\n case HttpStatusCodes.INTERNAL_SERVER_ERROR:\n return new InternalServerErrorException(message);\n case HttpStatusCodes.BAD_GATEWAY:\n return new BadGatewayException(message);\n case HttpStatusCodes.SERVICE_UNAVAILABLE:\n return new ServiceUnavailableException(message);\n case HttpStatusCodes.GATEWAY_TIMEOUT:\n return new GatewayTimeoutException(message);\n case HttpStatusCodes.INSUFFICIENT_STORAGE:\n return new InsufficientStorageException(message);\n default:\n return new HttpError(status, message || `HTTP Error ${status}`);\n }\n}\n\n/**\n * Type guard to check if an object has specific error properties.\n *\n * @param error - The object to check.\n * @returns True if object has error-like structure.\n */\nexport function hasErrorShape(\n error: unknown,\n): error is { message: string; status?: number; code?: string } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as any).message === \"string\"\n );\n}\n\n/**\n * Safely extracts message from any error type.\n *\n * @param error - Any error object or value.\n * @returns A string error message.\n */\nexport function getErrorMessage(error: unknown): string {\n if (typeof error === \"string\") {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (hasErrorShape(error)) {\n return error.message;\n }\n\n return \"Unknown error occurred\";\n}\n\n/**\n * Wraps a function and transforms any errors into HTTP errors.\n * Useful for API handlers to ensure consistent error responses.\n *\n * @param handler - The async function to wrap.\n * @returns A function that always returns or throws an HTTP error.\n */\nexport function withErrorHandling<T extends (...args: any[]) => Promise<any>>(\n handler: T,\n): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {\n return async (...args: Parameters<T>) => {\n try {\n return await handler(...args);\n } catch (error) {\n if (isHttpError(error)) {\n throw error;\n }\n\n // Log the original error (consider using a proper logger)\n getLogger().error(\"Caught error in handler:\", error);\n\n // Extract status code if it exists, otherwise use 500\n let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n if (hasErrorShape(error) && typeof error.status === \"number\") {\n status = error.status;\n }\n\n // Create appropriate HTTP error\n throw createHttpError(status, getErrorMessage(error));\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"exception.utils.js","sourceRoot":"","sources":["../../../src/utils/exception.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,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AO,wBAAwB,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAU;IAEV,OAAO,KAAK,EAAE,GAAG,IAAmB,EAAE,EAAE;QACtC,IAAI,CAAC;YACH,OAAO,MAAM,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,MAAM,KAAK,CAAC;YACd,CAAC;YAED,0DAA0D;YAC1D,SAAS,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,EAAE,yBAAyB,CAAC,CAAC;YAExD,sDAAsD;YACtD,IAAI,MAAM,GAAG,eAAe,CAAC,qBAAqB,CAAC;YACnD,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;gBAC7D,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;YACxB,CAAC;YAED,gCAAgC;YAChC,MAAM,eAAe,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACxD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { HttpStatusCodes } from './http-status-codes';\nimport { getLogger } from './logger.utils';\nimport { ErrorResponse } from './response.utils';\n\n/**\n * Generic HTTP error class used for custom exceptions with any status code.\n * Inherit this when you need to throw errors dynamically at runtime.\n */\nexport class HttpError extends ErrorResponse {\n /**\n * Creates a new HTTP error instance.\n * @param status - A valid HTTP status code (e.g., 400, 500).\n * @param message - The error message to return to the client.\n */\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\n/**\n * Represents a 500 Internal Server Error.\n * Use this for unexpected backend errors that are not caused by the client.\n */\nexport class InternalServerErrorException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Internal server error\".\n */\n constructor(message: string = 'Internal server error') {\n super(message);\n this.status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n }\n}\n\n/**\n * Represents a 401 Unauthorized Error.\n * Indicates that authentication is required and has failed or not been provided.\n */\nexport class UnauthorizedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unauthorized\".\n */\n constructor(message: string = 'Unauthorized') {\n super(message);\n this.status = HttpStatusCodes.UNAUTHORIZED;\n }\n}\n\n/**\n * Represents a 400 Bad Request Error.\n * Indicates that the client has sent invalid data (e.g., malformed request body).\n */\nexport class BadRequestException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad request\".\n */\n constructor(message: string = 'Bad request') {\n super(message);\n this.status = HttpStatusCodes.BAD_REQUEST;\n }\n}\n\n/**\n * Represents a 404 Not Found Error.\n * Used when a requested resource (e.g., user, file) could not be located.\n */\nexport class NotFoundException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Resource not found\".\n */\n constructor(message: string = 'Resource not found') {\n super(message);\n this.status = HttpStatusCodes.NOT_FOUND;\n }\n}\n\n/**\n * Represents a 403 Forbidden Error.\n * Indicates that the client is authenticated but not allowed to access the resource.\n */\nexport class ForbiddenException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Forbidden\".\n */\n constructor(message: string = 'Forbidden') {\n super(message);\n this.status = HttpStatusCodes.FORBIDDEN;\n }\n}\n\n/**\n * Represents a 409 Conflict Error.\n * Commonly used when a resource already exists or a versioning conflict occurs.\n */\nexport class ConflictException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Conflict\".\n */\n constructor(message: string = 'Conflict') {\n super(message);\n this.status = HttpStatusCodes.CONFLICT;\n }\n}\n\n/**\n * Represents a 502 Bad Gateway Error.\n * Used when the server receives an invalid response from an upstream server.\n */\nexport class BadGatewayException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad Gateway\".\n */\n constructor(message: string = 'Bad Gateway') {\n super(message);\n this.status = HttpStatusCodes.BAD_GATEWAY;\n }\n}\n\n/**\n * Represents a 429 Too Many Requests Error.\n * Returned when the client has hit a rate limit.\n */\nexport class TooManyRequestsException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Too many requests\".\n */\n constructor(message: string = 'Too many requests') {\n super(message);\n this.status = HttpStatusCodes.TOO_MANY_REQUESTS;\n }\n}\n\n/**\n * Represents a 503 Service Unavailable Error.\n * Indicates that the server is temporarily unavailable (e.g., for maintenance).\n */\nexport class ServiceUnavailableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Service Unavailable\".\n */\n constructor(message: string = 'Service Unavailable') {\n super(message);\n this.status = HttpStatusCodes.SERVICE_UNAVAILABLE;\n }\n}\n\n/**\n * Represents a 504 Gateway Timeout Error.\n * Returned when the server acting as a gateway times out waiting for a response.\n */\nexport class GatewayTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Gateway Timeout\".\n */\n constructor(message: string = 'Gateway Timeout') {\n super(message);\n this.status = HttpStatusCodes.GATEWAY_TIMEOUT;\n }\n}\n\n/**\n * Represents a 422 Unprocessable Entity Error.\n * Used when the server understands the content type but cannot process the contained instructions.\n */\nexport class UnprocessableEntityException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unprocessable Entity\".\n * @param details - Optional validation details or additional error context.\n */\n constructor(\n message: string = 'Unprocessable Entity',\n public details?: Record<string, any>\n ) {\n super(message);\n this.status = HttpStatusCodes.UNPROCESSABLE_ENTITY;\n }\n}\n\n/**\n * Represents a 405 Method Not Allowed Error.\n * Used when the request method is not supported for the requested resource.\n */\nexport class MethodNotAllowedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Method Not Allowed\".\n * @param allowedMethods - Optional array of allowed HTTP methods.\n */\n constructor(\n message: string = 'Method Not Allowed',\n public allowedMethods?: string[]\n ) {\n super(message);\n this.status = HttpStatusCodes.METHOD_NOT_ALLOWED;\n }\n}\n\n/**\n * Represents a 406 Not Acceptable Error.\n * Used when the server cannot produce a response matching the client's accepted content types.\n */\nexport class NotAcceptableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Not Acceptable\".\n */\n constructor(message: string = 'Not Acceptable') {\n super(message);\n this.status = HttpStatusCodes.NOT_ACCEPTABLE;\n }\n}\n\n/**\n * Represents a 408 Request Timeout Error.\n * Used when the server times out waiting for the client to send a request.\n */\nexport class RequestTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Request Timeout\".\n */\n constructor(message: string = 'Request Timeout') {\n super(message);\n this.status = HttpStatusCodes.REQUEST_TIMEOUT;\n }\n}\n\n/**\n * Represents a 415 Unsupported Media Type Error.\n * Used when the request's Content-Type is not supported.\n */\nexport class UnsupportedMediaTypeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unsupported Media Type\".\n */\n constructor(message: string = 'Unsupported Media Type') {\n super(message);\n this.status = HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;\n }\n}\n\n/**\n * Represents a 413 Payload Too Large Error.\n * Used when the request body exceeds server limits.\n */\nexport class PayloadTooLargeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Payload Too Large\".\n */\n constructor(message: string = 'Payload Too Large') {\n super(message);\n this.status = HttpStatusCodes.PAYLOAD_TOO_LARGE;\n }\n}\n\n/**\n * Represents a 507 Insufficient Storage Error.\n * Used when the server has insufficient storage to complete the request.\n */\nexport class InsufficientStorageException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Insufficient Storage\".\n */\n constructor(message: string = 'Insufficient Storage') {\n super(message);\n this.status = HttpStatusCodes.INSUFFICIENT_STORAGE;\n }\n}\n\n/**\n * Checks if an error is an instance of HttpError or its subclasses.\n *\n * @param error - The error to check.\n * @returns True if the error is an HttpError, false otherwise.\n */\nexport function isHttpError(error: unknown): error is ErrorResponse {\n return error instanceof ErrorResponse;\n}\n\n/**\n * Creates an HTTP error with the specified status code and message.\n * Factory function for creating appropriate HTTP error instances.\n *\n * @param status - HTTP status code.\n * @param message - Optional custom error message.\n * @returns An instance of the appropriate HTTP error class.\n */\nexport function createHttpError(status: number, message?: string): ErrorResponse {\n switch (status) {\n case HttpStatusCodes.BAD_REQUEST:\n return new BadRequestException(message);\n case HttpStatusCodes.UNAUTHORIZED:\n return new UnauthorizedException(message);\n case HttpStatusCodes.FORBIDDEN:\n return new ForbiddenException(message);\n case HttpStatusCodes.NOT_FOUND:\n return new NotFoundException(message);\n case HttpStatusCodes.METHOD_NOT_ALLOWED:\n return new MethodNotAllowedException(message);\n case HttpStatusCodes.NOT_ACCEPTABLE:\n return new NotAcceptableException(message);\n case HttpStatusCodes.REQUEST_TIMEOUT:\n return new RequestTimeoutException(message);\n case HttpStatusCodes.CONFLICT:\n return new ConflictException(message);\n case HttpStatusCodes.GONE:\n return new HttpError(HttpStatusCodes.GONE, message || 'Gone');\n case HttpStatusCodes.PAYLOAD_TOO_LARGE:\n return new PayloadTooLargeException(message);\n case HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:\n return new UnsupportedMediaTypeException(message);\n case HttpStatusCodes.UNPROCESSABLE_ENTITY:\n return new UnprocessableEntityException(message);\n case HttpStatusCodes.TOO_MANY_REQUESTS:\n return new TooManyRequestsException(message);\n case HttpStatusCodes.INTERNAL_SERVER_ERROR:\n return new InternalServerErrorException(message);\n case HttpStatusCodes.BAD_GATEWAY:\n return new BadGatewayException(message);\n case HttpStatusCodes.SERVICE_UNAVAILABLE:\n return new ServiceUnavailableException(message);\n case HttpStatusCodes.GATEWAY_TIMEOUT:\n return new GatewayTimeoutException(message);\n case HttpStatusCodes.INSUFFICIENT_STORAGE:\n return new InsufficientStorageException(message);\n default:\n return new HttpError(status, message || `HTTP Error ${status}`);\n }\n}\n\n/**\n * Type guard to check if an object has specific error properties.\n *\n * @param error - The object to check.\n * @returns True if object has error-like structure.\n */\nexport function hasErrorShape(error: unknown): error is { message: string; status?: number; code?: string } {\n return (\n typeof error === 'object' && error !== null && 'message' in error && typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Safely extracts message from any error type.\n *\n * @param error - Any error object or value.\n * @returns A string error message.\n */\nexport function getErrorMessage(error: unknown): string {\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (hasErrorShape(error)) {\n return error.message;\n }\n\n return 'Unknown error occurred';\n}\n\n/**\n * Wraps a function and transforms any errors into HTTP errors.\n * Useful for API handlers to ensure consistent error responses.\n *\n * @param handler - The async function to wrap.\n * @returns A function that always returns or throws an HTTP error.\n */\nexport function withErrorHandling<T extends (...args: any[]) => Promise<any>>(\n handler: T\n): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {\n return async (...args: Parameters<T>) => {\n try {\n return await handler(...args);\n } catch (error) {\n if (isHttpError(error)) {\n throw error;\n }\n\n // Log the original error (consider using a proper logger)\n getLogger().error({ error }, 'Caught error in handler');\n\n // Extract status code if it exists, otherwise use 500\n let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n if (hasErrorShape(error) && typeof error.status === 'number') {\n status = error.status;\n }\n\n // Create appropriate HTTP error\n throw createHttpError(status, getErrorMessage(error));\n }\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BufferEncoding } from
|
|
2
|
-
import { Stats } from
|
|
1
|
+
import { BufferEncoding } from './crypto.utils';
|
|
2
|
+
import { Stats } from 'fs';
|
|
3
3
|
/**
|
|
4
4
|
* Checks whether a file or directory exists at the given path.
|
|
5
5
|
*
|
|
@@ -91,7 +91,7 @@ export declare function getFileStats(path: string): Promise<Stats | null>;
|
|
|
91
91
|
* @param {string | Buffer} [options.content] - Optional content to write to the file.
|
|
92
92
|
* @returns {Promise<string>} Path to the created temporary file.
|
|
93
93
|
*/
|
|
94
|
-
export declare function createTempFile({ prefix, extension, dir, content
|
|
94
|
+
export declare function createTempFile({ prefix, extension, dir, content }?: {
|
|
95
95
|
prefix?: string;
|
|
96
96
|
extension?: string;
|
|
97
97
|
dir?: string;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import fs from
|
|
2
|
-
import { createReadStream, createWriteStream } from
|
|
3
|
-
import { tmpdir } from
|
|
4
|
-
import path from
|
|
5
|
-
import { pipeline } from
|
|
6
|
-
import { randomUUID } from
|
|
1
|
+
import fs from 'fs/promises';
|
|
2
|
+
import { createReadStream, createWriteStream } from 'fs';
|
|
3
|
+
import { tmpdir } from 'os';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { pipeline } from 'stream/promises';
|
|
6
|
+
import { randomUUID } from 'crypto';
|
|
7
7
|
/**
|
|
8
8
|
* Checks whether a file or directory exists at the given path.
|
|
9
9
|
*
|
|
@@ -28,7 +28,7 @@ export async function fileExists(path) {
|
|
|
28
28
|
*/
|
|
29
29
|
export async function readJsonFile(path) {
|
|
30
30
|
try {
|
|
31
|
-
const data = await fs.readFile(path,
|
|
31
|
+
const data = await fs.readFile(path, 'utf-8');
|
|
32
32
|
return JSON.parse(data);
|
|
33
33
|
}
|
|
34
34
|
catch (_a) {
|
|
@@ -45,7 +45,7 @@ export async function readJsonFile(path) {
|
|
|
45
45
|
*/
|
|
46
46
|
export async function writeJsonFile(path, data, space = 2) {
|
|
47
47
|
const json = JSON.stringify(data, null, space);
|
|
48
|
-
await fs.writeFile(path, json,
|
|
48
|
+
await fs.writeFile(path, json, 'utf-8');
|
|
49
49
|
}
|
|
50
50
|
/**
|
|
51
51
|
* Deletes a file if it exists.
|
|
@@ -59,7 +59,7 @@ export async function deleteFileIfExists(path) {
|
|
|
59
59
|
return true;
|
|
60
60
|
}
|
|
61
61
|
catch (err) {
|
|
62
|
-
if (err.code ===
|
|
62
|
+
if (err.code === 'ENOENT')
|
|
63
63
|
return true;
|
|
64
64
|
return false;
|
|
65
65
|
}
|
|
@@ -71,7 +71,7 @@ export async function deleteFileIfExists(path) {
|
|
|
71
71
|
* @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
|
|
72
72
|
* @returns {Promise<string | null>} The file contents, or `null` if reading fails.
|
|
73
73
|
*/
|
|
74
|
-
export async function readTextFile(path, encoding =
|
|
74
|
+
export async function readTextFile(path, encoding = 'utf-8') {
|
|
75
75
|
try {
|
|
76
76
|
return await fs.readFile(path, encoding);
|
|
77
77
|
}
|
|
@@ -87,7 +87,7 @@ export async function readTextFile(path, encoding = "utf-8") {
|
|
|
87
87
|
* @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
|
|
88
88
|
* @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
|
|
89
89
|
*/
|
|
90
|
-
export async function writeTextFile(path, content, encoding =
|
|
90
|
+
export async function writeTextFile(path, content, encoding = 'utf-8') {
|
|
91
91
|
try {
|
|
92
92
|
await fs.writeFile(path, content, encoding);
|
|
93
93
|
return true;
|
|
@@ -104,7 +104,7 @@ export async function writeTextFile(path, content, encoding = "utf-8") {
|
|
|
104
104
|
* @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
|
|
105
105
|
* @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
|
|
106
106
|
*/
|
|
107
|
-
export async function appendTextFile(path, content, encoding =
|
|
107
|
+
export async function appendTextFile(path, content, encoding = 'utf-8') {
|
|
108
108
|
try {
|
|
109
109
|
await fs.appendFile(path, content, encoding);
|
|
110
110
|
return true;
|
|
@@ -179,19 +179,15 @@ export async function getFileStats(path) {
|
|
|
179
179
|
* @param {string | Buffer} [options.content] - Optional content to write to the file.
|
|
180
180
|
* @returns {Promise<string>} Path to the created temporary file.
|
|
181
181
|
*/
|
|
182
|
-
export async function createTempFile({ prefix =
|
|
183
|
-
const ext = extension
|
|
184
|
-
? extension.startsWith(".")
|
|
185
|
-
? extension
|
|
186
|
-
: `.${extension}`
|
|
187
|
-
: "";
|
|
182
|
+
export async function createTempFile({ prefix = 'tmp-', extension = '', dir = tmpdir(), content } = {}) {
|
|
183
|
+
const ext = extension ? (extension.startsWith('.') ? extension : `.${extension}`) : '';
|
|
188
184
|
const filename = `${prefix}${randomUUID()}${ext}`;
|
|
189
185
|
const filepath = path.join(dir, filename);
|
|
190
186
|
if (content) {
|
|
191
187
|
await fs.writeFile(filepath, content);
|
|
192
188
|
}
|
|
193
189
|
else {
|
|
194
|
-
await fs.writeFile(filepath,
|
|
190
|
+
await fs.writeFile(filepath, '');
|
|
195
191
|
}
|
|
196
192
|
return filepath;
|
|
197
193
|
}
|
|
@@ -231,10 +227,10 @@ export async function readDirectory(dirPath, options = {}) {
|
|
|
231
227
|
const files = await fs.readdir(dirPath);
|
|
232
228
|
let result = files;
|
|
233
229
|
if (options.filter) {
|
|
234
|
-
result = result.filter(
|
|
230
|
+
result = result.filter(file => options.filter.test(file));
|
|
235
231
|
}
|
|
236
232
|
if (options.fullPaths) {
|
|
237
|
-
result = result.map(
|
|
233
|
+
result = result.map(file => path.join(dirPath, file));
|
|
238
234
|
}
|
|
239
235
|
return result;
|
|
240
236
|
}
|
|
@@ -252,7 +248,7 @@ export async function createDirectory(dirPath, recursive = true) {
|
|
|
252
248
|
}
|
|
253
249
|
catch (err) {
|
|
254
250
|
// Consider it success if directory already exists
|
|
255
|
-
return err.code ===
|
|
251
|
+
return err.code === 'EEXIST';
|
|
256
252
|
}
|
|
257
253
|
}
|
|
258
254
|
/**
|
|
@@ -264,7 +260,7 @@ export async function createDirectory(dirPath, recursive = true) {
|
|
|
264
260
|
*/
|
|
265
261
|
export async function safeReadJsonFile(path) {
|
|
266
262
|
try {
|
|
267
|
-
const content = await fs.readFile(path,
|
|
263
|
+
const content = await fs.readFile(path, 'utf-8');
|
|
268
264
|
try {
|
|
269
265
|
const data = JSON.parse(content);
|
|
270
266
|
return { data, error: null };
|
|
@@ -272,14 +268,14 @@ export async function safeReadJsonFile(path) {
|
|
|
272
268
|
catch (error) {
|
|
273
269
|
return {
|
|
274
270
|
data: null,
|
|
275
|
-
error: new Error(`Invalid JSON in file ${path}: ${error.message}`)
|
|
271
|
+
error: new Error(`Invalid JSON in file ${path}: ${error.message}`)
|
|
276
272
|
};
|
|
277
273
|
}
|
|
278
274
|
}
|
|
279
275
|
catch (error) {
|
|
280
276
|
return {
|
|
281
277
|
data: null,
|
|
282
|
-
error: new Error(`Failed to read file ${path}: ${error.message}`)
|
|
278
|
+
error: new Error(`Failed to read file ${path}: ${error.message}`)
|
|
283
279
|
};
|
|
284
280
|
}
|
|
285
281
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs.utils.js","sourceRoot":"","sources":["../../../src/utils/fs.utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAS,MAAM,IAAI,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC5B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,IAAY;IAC3C,IAAI,CAAC;QACH,MAAM,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAU,IAAY;IACtD,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAM,CAAC;IAC/B,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,IAAY,EACZ,IAAS,EACT,KAAK,GA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AE,IAAI;gBACV,KAAK,EAAE,IAAI,KAAK,CAAC,wBAAwB,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC;aACnE,CAAC;QACJ,CAAC;IACH,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,OAAO;YACL,IAAI,EAAE,IAAI;YACV,KAAK,EAAE,IAAI,KAAK,CAAC,uBAAuB,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC;SAClE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,IAAY;IACvC,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;IACvB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAY;IAC5C,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,CAAC,CAAC,CAAC;IACZ,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAY;IAC/C,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACjC,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { BufferEncoding } from \"./crypto.utils\";\nimport fs from \"fs/promises\";\nimport { createReadStream, createWriteStream, Stats } from \"fs\";\nimport { tmpdir } from \"os\";\nimport path from \"path\";\nimport { pipeline } from \"stream/promises\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Checks whether a file or directory exists at the given path.\n *\n * @param {string} path - The file or directory path to check.\n * @returns {Promise<boolean>} Resolves to `true` if the path exists, `false` otherwise.\n */\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reads and parses a JSON file from the specified path.\n *\n * @typeParam T - The expected type of the parsed JSON object.\n * @param {string} path - The path to the JSON file.\n * @returns {Promise<T | null>} The parsed object, or `null` if reading or parsing fails.\n */\nexport async function readJsonFile<T = any>(path: string): Promise<T | null> {\n try {\n const data = await fs.readFile(path, \"utf-8\");\n return JSON.parse(data) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Writes a JavaScript object to a file as formatted JSON.\n *\n * @param {string} path - The destination file path.\n * @param {any} data - The object to serialize and write.\n * @param {number} [space=2] - Number of spaces for JSON formatting.\n * @returns {Promise<void>} Resolves when writing is complete.\n */\nexport async function writeJsonFile(\n path: string,\n data: any,\n space = 2,\n): Promise<void> {\n const json = JSON.stringify(data, null, space);\n await fs.writeFile(path, json, \"utf-8\");\n}\n\n/**\n * Deletes a file if it exists.\n *\n * @param {string} path - The file path to delete.\n * @returns {Promise<boolean>} Resolves to `true` if the file was deleted or didn't exist, `false` if deletion failed.\n */\nexport async function deleteFileIfExists(path: string): Promise<boolean> {\n try {\n await fs.unlink(path);\n return true;\n } catch (err: any) {\n if (err.code === \"ENOENT\") return true;\n return false;\n }\n}\n\n/**\n * Reads a text file from the specified path.\n *\n * @param {string} path - The path to the text file.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<string | null>} The file contents, or `null` if reading fails.\n */\nexport async function readTextFile(\n path: string,\n encoding: BufferEncoding = \"utf-8\",\n): Promise<string | null> {\n try {\n return await fs.readFile(path, encoding);\n } catch {\n return null;\n }\n}\n\n/**\n * Writes text content to a file.\n *\n * @param {string} path - The destination file path.\n * @param {string} content - The text content to write.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function writeTextFile(\n path: string,\n content: string,\n encoding: BufferEncoding = \"utf-8\",\n): Promise<boolean> {\n try {\n await fs.writeFile(path, content, encoding);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Appends text content to a file.\n *\n * @param {string} path - The file path to append to.\n * @param {string} content - The text content to append.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function appendTextFile(\n path: string,\n content: string,\n encoding: BufferEncoding = \"utf-8\",\n): Promise<boolean> {\n try {\n await fs.appendFile(path, content, encoding);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Copies a file from source to destination.\n *\n * @param {string} source - Source file path.\n * @param {string} destination - Destination file path.\n * @param {boolean} [overwrite=false] - Whether to overwrite if destination exists.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function copyFile(\n source: string,\n destination: string,\n overwrite = false,\n): Promise<boolean> {\n try {\n const flags = overwrite ? 0 : fs.constants.COPYFILE_EXCL;\n await fs.copyFile(source, destination, flags);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Renames/moves a file.\n *\n * @param {string} oldPath - Current file path.\n * @param {string} newPath - New file path.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function moveFile(\n oldPath: string,\n newPath: string,\n): Promise<boolean> {\n try {\n await fs.rename(oldPath, newPath);\n return true;\n } catch {\n // If rename fails (e.g., across devices), try copy+delete\n try {\n await fs.copyFile(oldPath, newPath);\n await fs.unlink(oldPath);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Gets file stats if the file exists.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<fs.Stats | null>} File stats object or null if file doesn't exist.\n */\nexport async function getFileStats(path: string): Promise<Stats | null> {\n try {\n return await fs.stat(path);\n } catch {\n return null;\n }\n}\n\n/**\n * Creates a temporary file with optional content.\n *\n * @param {object} [options] - Options for creating the temp file.\n * @param {string} [options.prefix=\"tmp-\"] - Filename prefix.\n * @param {string} [options.extension=\"\"] - File extension.\n * @param {string} [options.dir] - Directory to create the file in (defaults to OS temp dir).\n * @param {string | Buffer} [options.content] - Optional content to write to the file.\n * @returns {Promise<string>} Path to the created temporary file.\n */\nexport async function createTempFile({\n prefix = \"tmp-\",\n extension = \"\",\n dir = tmpdir(),\n content,\n}: {\n prefix?: string;\n extension?: string;\n dir?: string;\n content?: string | Buffer;\n} = {}): Promise<string> {\n const ext = extension\n ? extension.startsWith(\".\")\n ? extension\n : `.${extension}`\n : \"\";\n const filename = `${prefix}${randomUUID()}${ext}`;\n const filepath = path.join(dir, filename);\n\n if (content) {\n await fs.writeFile(filepath, content);\n } else {\n await fs.writeFile(filepath, \"\");\n }\n\n return filepath;\n}\n\n/**\n * Streams a file from source to destination.\n * Useful for large files to avoid loading the entire file into memory.\n *\n * @param {string} source - Source file path.\n * @param {string} destination - Destination file path.\n * @returns {Promise<void>} Resolves when streaming completes.\n * @throws {Error} If streaming fails.\n */\nexport async function streamFile(\n source: string,\n destination: string,\n): Promise<void> {\n const readStream = createReadStream(source);\n const writeStream = createWriteStream(destination);\n\n try {\n await pipeline(readStream, writeStream);\n } catch (error) {\n // Ensure both streams are closed in case of error\n readStream.destroy();\n writeStream.destroy();\n throw error;\n }\n}\n\n/**\n * Reads a directory and returns file names.\n *\n * @param {string} dirPath - Path to the directory.\n * @param {object} [options] - Options for reading the directory.\n * @param {boolean} [options.fullPaths=false] - Whether to return full paths.\n * @param {RegExp} [options.filter] - Optional regex to filter files.\n * @returns {Promise<string[]>} Array of file names or paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function readDirectory(\n dirPath: string,\n options: { fullPaths?: boolean; filter?: RegExp } = {},\n): Promise<string[]> {\n const files = await fs.readdir(dirPath);\n\n let result = files;\n\n if (options.filter) {\n result = result.filter((file) => options.filter!.test(file));\n }\n\n if (options.fullPaths) {\n result = result.map((file) => path.join(dirPath, file));\n }\n\n return result;\n}\n\n/**\n * Creates a directory if it doesn't exist.\n *\n * @param {string} dirPath - Path to the directory.\n * @param {boolean} [recursive=true] - Whether to create parent directories.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function createDirectory(\n dirPath: string,\n recursive = true,\n): Promise<boolean> {\n try {\n await fs.mkdir(dirPath, { recursive });\n return true;\n } catch (err: any) {\n // Consider it success if directory already exists\n return err.code === \"EEXIST\";\n }\n}\n\n/**\n * Safely reads and parses a JSON file with error details.\n *\n * @typeParam T - The expected type of the parsed JSON object.\n * @param {string} path - The path to the JSON file.\n * @returns {Promise<{ data: T | null; error: Error | null }>} Object with data and error properties.\n */\nexport async function safeReadJsonFile<T = any>(\n path: string,\n): Promise<{ data: T | null; error: Error | null }> {\n try {\n const content = await fs.readFile(path, \"utf-8\");\n try {\n const data = JSON.parse(content) as T;\n return { data, error: null };\n } catch (error: any) {\n return {\n data: null,\n error: new Error(`Invalid JSON in file ${path}: ${error.message}`),\n };\n }\n } catch (error: any) {\n return {\n data: null,\n error: new Error(`Failed to read file ${path}: ${error.message}`),\n };\n }\n}\n\n/**\n * Checks if a path points to a file (not a directory).\n *\n * @param {string} path - Path to check.\n * @returns {Promise<boolean>} True if the path is a file, false otherwise.\n */\nexport async function isFile(path: string): Promise<boolean> {\n try {\n const stat = await fs.stat(path);\n return stat.isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Gets the size of a file in bytes.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<number>} Size in bytes or -1 if file doesn't exist.\n */\nexport async function getFileSize(path: string): Promise<number> {\n try {\n const stat = await fs.stat(path);\n return stat.size;\n } catch {\n return -1;\n }\n}\n\n/**\n * Reads a file as a Buffer.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<Buffer | null>} File contents as Buffer or null if reading fails.\n */\nexport async function readFileBuffer(path: string): Promise<Buffer | null> {\n try {\n return await fs.readFile(path);\n } catch {\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fs.utils.js","sourceRoot":"","sources":["../../../src/utils/fs.utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAS,MAAM,IAAI,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC5B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,IAAY;IAC3C,IAAI,CAAC;QACH,MAAM,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAU,IAAY;IACtD,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAM,CAAC;IAC/B,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,IAAY,EAAE,IAAS,EAAE,KAAK,GAAG,CAAC;IACpE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC/C,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAA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L,IAAI,EAAE,IAAI;YACV,KAAK,EAAE,IAAI,KAAK,CAAC,uBAAuB,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC;SAClE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,IAAY;IACvC,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;IACvB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAY;IAC5C,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,CAAC,CAAC,CAAC;IACZ,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAY;IAC/C,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACjC,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { BufferEncoding } from './crypto.utils';\nimport fs from 'fs/promises';\nimport { createReadStream, createWriteStream, Stats } from 'fs';\nimport { tmpdir } from 'os';\nimport path from 'path';\nimport { pipeline } from 'stream/promises';\nimport { randomUUID } from 'crypto';\n\n/**\n * Checks whether a file or directory exists at the given path.\n *\n * @param {string} path - The file or directory path to check.\n * @returns {Promise<boolean>} Resolves to `true` if the path exists, `false` otherwise.\n */\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reads and parses a JSON file from the specified path.\n *\n * @typeParam T - The expected type of the parsed JSON object.\n * @param {string} path - The path to the JSON file.\n * @returns {Promise<T | null>} The parsed object, or `null` if reading or parsing fails.\n */\nexport async function readJsonFile<T = any>(path: string): Promise<T | null> {\n try {\n const data = await fs.readFile(path, 'utf-8');\n return JSON.parse(data) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Writes a JavaScript object to a file as formatted JSON.\n *\n * @param {string} path - The destination file path.\n * @param {any} data - The object to serialize and write.\n * @param {number} [space=2] - Number of spaces for JSON formatting.\n * @returns {Promise<void>} Resolves when writing is complete.\n */\nexport async function writeJsonFile(path: string, data: any, space = 2): Promise<void> {\n const json = JSON.stringify(data, null, space);\n await fs.writeFile(path, json, 'utf-8');\n}\n\n/**\n * Deletes a file if it exists.\n *\n * @param {string} path - The file path to delete.\n * @returns {Promise<boolean>} Resolves to `true` if the file was deleted or didn't exist, `false` if deletion failed.\n */\nexport async function deleteFileIfExists(path: string): Promise<boolean> {\n try {\n await fs.unlink(path);\n return true;\n } catch (err: any) {\n if (err.code === 'ENOENT') return true;\n return false;\n }\n}\n\n/**\n * Reads a text file from the specified path.\n *\n * @param {string} path - The path to the text file.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<string | null>} The file contents, or `null` if reading fails.\n */\nexport async function readTextFile(path: string, encoding: BufferEncoding = 'utf-8'): Promise<string | null> {\n try {\n return await fs.readFile(path, encoding);\n } catch {\n return null;\n }\n}\n\n/**\n * Writes text content to a file.\n *\n * @param {string} path - The destination file path.\n * @param {string} content - The text content to write.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function writeTextFile(\n path: string,\n content: string,\n encoding: BufferEncoding = 'utf-8'\n): Promise<boolean> {\n try {\n await fs.writeFile(path, content, encoding);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Appends text content to a file.\n *\n * @param {string} path - The file path to append to.\n * @param {string} content - The text content to append.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function appendTextFile(\n path: string,\n content: string,\n encoding: BufferEncoding = 'utf-8'\n): Promise<boolean> {\n try {\n await fs.appendFile(path, content, encoding);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Copies a file from source to destination.\n *\n * @param {string} source - Source file path.\n * @param {string} destination - Destination file path.\n * @param {boolean} [overwrite=false] - Whether to overwrite if destination exists.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function copyFile(source: string, destination: string, overwrite = false): Promise<boolean> {\n try {\n const flags = overwrite ? 0 : fs.constants.COPYFILE_EXCL;\n await fs.copyFile(source, destination, flags);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Renames/moves a file.\n *\n * @param {string} oldPath - Current file path.\n * @param {string} newPath - New file path.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function moveFile(oldPath: string, newPath: string): Promise<boolean> {\n try {\n await fs.rename(oldPath, newPath);\n return true;\n } catch {\n // If rename fails (e.g., across devices), try copy+delete\n try {\n await fs.copyFile(oldPath, newPath);\n await fs.unlink(oldPath);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Gets file stats if the file exists.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<fs.Stats | null>} File stats object or null if file doesn't exist.\n */\nexport async function getFileStats(path: string): Promise<Stats | null> {\n try {\n return await fs.stat(path);\n } catch {\n return null;\n }\n}\n\n/**\n * Creates a temporary file with optional content.\n *\n * @param {object} [options] - Options for creating the temp file.\n * @param {string} [options.prefix=\"tmp-\"] - Filename prefix.\n * @param {string} [options.extension=\"\"] - File extension.\n * @param {string} [options.dir] - Directory to create the file in (defaults to OS temp dir).\n * @param {string | Buffer} [options.content] - Optional content to write to the file.\n * @returns {Promise<string>} Path to the created temporary file.\n */\nexport async function createTempFile({\n prefix = 'tmp-',\n extension = '',\n dir = tmpdir(),\n content\n}: {\n prefix?: string;\n extension?: string;\n dir?: string;\n content?: string | Buffer;\n} = {}): Promise<string> {\n const ext = extension ? (extension.startsWith('.') ? extension : `.${extension}`) : '';\n const filename = `${prefix}${randomUUID()}${ext}`;\n const filepath = path.join(dir, filename);\n\n if (content) {\n await fs.writeFile(filepath, content);\n } else {\n await fs.writeFile(filepath, '');\n }\n\n return filepath;\n}\n\n/**\n * Streams a file from source to destination.\n * Useful for large files to avoid loading the entire file into memory.\n *\n * @param {string} source - Source file path.\n * @param {string} destination - Destination file path.\n * @returns {Promise<void>} Resolves when streaming completes.\n * @throws {Error} If streaming fails.\n */\nexport async function streamFile(source: string, destination: string): Promise<void> {\n const readStream = createReadStream(source);\n const writeStream = createWriteStream(destination);\n\n try {\n await pipeline(readStream, writeStream);\n } catch (error) {\n // Ensure both streams are closed in case of error\n readStream.destroy();\n writeStream.destroy();\n throw error;\n }\n}\n\n/**\n * Reads a directory and returns file names.\n *\n * @param {string} dirPath - Path to the directory.\n * @param {object} [options] - Options for reading the directory.\n * @param {boolean} [options.fullPaths=false] - Whether to return full paths.\n * @param {RegExp} [options.filter] - Optional regex to filter files.\n * @returns {Promise<string[]>} Array of file names or paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function readDirectory(\n dirPath: string,\n options: { fullPaths?: boolean; filter?: RegExp } = {}\n): Promise<string[]> {\n const files = await fs.readdir(dirPath);\n\n let result = files;\n\n if (options.filter) {\n result = result.filter(file => options.filter!.test(file));\n }\n\n if (options.fullPaths) {\n result = result.map(file => path.join(dirPath, file));\n }\n\n return result;\n}\n\n/**\n * Creates a directory if it doesn't exist.\n *\n * @param {string} dirPath - Path to the directory.\n * @param {boolean} [recursive=true] - Whether to create parent directories.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function createDirectory(dirPath: string, recursive = true): Promise<boolean> {\n try {\n await fs.mkdir(dirPath, { recursive });\n return true;\n } catch (err: any) {\n // Consider it success if directory already exists\n return err.code === 'EEXIST';\n }\n}\n\n/**\n * Safely reads and parses a JSON file with error details.\n *\n * @typeParam T - The expected type of the parsed JSON object.\n * @param {string} path - The path to the JSON file.\n * @returns {Promise<{ data: T | null; error: Error | null }>} Object with data and error properties.\n */\nexport async function safeReadJsonFile<T = any>(path: string): Promise<{ data: T | null; error: Error | null }> {\n try {\n const content = await fs.readFile(path, 'utf-8');\n try {\n const data = JSON.parse(content) as T;\n return { data, error: null };\n } catch (error: any) {\n return {\n data: null,\n error: new Error(`Invalid JSON in file ${path}: ${error.message}`)\n };\n }\n } catch (error: any) {\n return {\n data: null,\n error: new Error(`Failed to read file ${path}: ${error.message}`)\n };\n }\n}\n\n/**\n * Checks if a path points to a file (not a directory).\n *\n * @param {string} path - Path to check.\n * @returns {Promise<boolean>} True if the path is a file, false otherwise.\n */\nexport async function isFile(path: string): Promise<boolean> {\n try {\n const stat = await fs.stat(path);\n return stat.isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Gets the size of a file in bytes.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<number>} Size in bytes or -1 if file doesn't exist.\n */\nexport async function getFileSize(path: string): Promise<number> {\n try {\n const stat = await fs.stat(path);\n return stat.size;\n } catch {\n return -1;\n }\n}\n\n/**\n * Reads a file as a Buffer.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<Buffer | null>} File contents as Buffer or null if reading fails.\n */\nexport async function readFileBuffer(path: string): Promise<Buffer | null> {\n try {\n return await fs.readFile(path);\n } catch {\n return null;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http-status-codes.js","sourceRoot":"","sources":["../../../src/utils/http-status-codes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAN,IAAY,eAwUX;AAxUD,WAAY,eAAe;IACzB,oBAAoB;IACpB;;OAEG;IACH,+DAAc,CAAA;I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IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,2FAA4B,CAAA;IAE5B;;OAEG;IACH,6GAAqC,CAAA;IAErC;;OAEG;IACH,mFAAwB,CAAA;IAExB;;OAEG;IACH,qEAAiB,CAAA;IAEjB;;OAEG;IACH,2GAAoC,CAAA;IAEpC;;;OAGG;IACH,2EAAoB,CAAA;IAEpB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,2DAAY,CAAA;IAEZ;;OAEG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,+EAAsB,CAAA;IAEtB;;OAEG;IACH,yFAA2B,CAAA;IAE3B;;OAEG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,6GAAqC,CAAA;IAErC;;OAEG;IACH,yGAAmC,CAAA;IAEnC,mBAAmB;IACnB;;OAEG;IACH,yFAA2B,CAAA;IAE3B;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,qEAAiB,CAAA;IAEjB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,mGAAgC,CAAA;IAEhC;;OAEG;IACH,6FAA6B,CAAA;IAE7B;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,yEAAmB,CAAA;IAEnB;;OAEG;IACH,uEAAkB,CAAA;IAElB;;OAEG;IACH,6GAAqC,CAAA;AACvC,CAAC,EAxUW,eAAe,KAAf,eAAe,QAwU1B","sourcesContent":["/**\n * Complete HTTP status codes enum with descriptions.\n * For use with API responses and error handling.\n */\nexport enum HttpStatusCodes {\n // 1xx Informational\n /**\n * The server has received the request headers and the client should proceed to send the request body.\n */\n CONTINUE = 100,\n\n /**\n * The server is switching protocols according to the client's request.\n */\n SWITCHING_PROTOCOLS = 101,\n\n /**\n * Server has received the request and is still processing it.\n */\n PROCESSING = 102,\n\n /**\n * The server is sending preliminary headers while preparing the final response.\n */\n EARLY_HINTS = 103,\n\n // 2xx Success\n /**\n * The request succeeded. The result meaning depends on the HTTP method used.\n */\n OK = 200,\n\n /**\n * The request succeeded and a new resource was created as a result.\n */\n CREATED = 201,\n\n /**\n * The request has been received but not yet acted upon.\n */\n ACCEPTED = 202,\n\n /**\n * The returned information is from a third-party source, not the origin server.\n */\n NON_AUTHORITATIVE_INFORMATION = 203,\n\n /**\n * The request succeeded but there's no content to send in the response.\n */\n NO_CONTENT = 204,\n\n /**\n * The client should reset the document view that caused this request.\n */\n RESET_CONTENT = 205,\n\n /**\n * The server is delivering only part of the resource due to a range header sent by the client.\n */\n PARTIAL_CONTENT = 206,\n\n /**\n * Conveys information about multiple resources, for complex operations.\n */\n MULTI_STATUS = 207,\n\n /**\n * The members of a DAV binding have already been enumerated and are not included in the response.\n */\n ALREADY_REPORTED = 208,\n\n /**\n * The server has fulfilled a request for the resource, and the response represents the result of one or more instance-manipulations.\n */\n IM_USED = 226,\n\n // 3xx Redirection\n /**\n * The request has more than one possible response and the client should choose one.\n */\n MULTIPLE_CHOICES = 300,\n\n /**\n * The resource has been permanently moved to a new URL.\n */\n MOVED_PERMANENTLY = 301,\n\n /**\n * The resource has been temporarily moved to another URL.\n */\n MOVED_TEMPORARILY = 302,\n\n /**\n * The response to the request can be found under another URI using the GET method.\n */\n SEE_OTHER = 303,\n\n /**\n * The resource hasn't been modified since the last request.\n */\n NOT_MODIFIED = 304,\n\n /**\n * @deprecated\n * Response must be accessed through a proxy.\n */\n USE_PROXY = 305,\n\n /**\n * The resource is temporarily available at a different URI, using the same HTTP method.\n */\n TEMPORARY_REDIRECT = 307,\n\n /**\n * The resource has been permanently moved to another URL, using the same HTTP method.\n */\n PERMANENT_REDIRECT = 308,\n\n // 4xx Client Error\n /**\n * The server cannot process the request due to a client error (malformed request).\n */\n BAD_REQUEST = 400,\n\n /**\n * Authentication is required and has failed or not been provided.\n */\n UNAUTHORIZED = 401,\n\n /**\n * Reserved for future use, originally intended for digital payment systems.\n */\n PAYMENT_REQUIRED = 402,\n\n /**\n * The client doesn't have permission to access the requested resource.\n */\n FORBIDDEN = 403,\n\n /**\n * The requested resource could not be found on the server.\n */\n NOT_FOUND = 404,\n\n /**\n * The request method is not supported for the requested resource.\n */\n METHOD_NOT_ALLOWED = 405,\n\n /**\n * The server can't provide a response matching the list of acceptable values in the client's headers.\n */\n NOT_ACCEPTABLE = 406,\n\n /**\n * Authentication by a proxy is required.\n */\n PROXY_AUTHENTICATION_REQUIRED = 407,\n\n /**\n * The server timed out waiting for the request.\n */\n REQUEST_TIMEOUT = 408,\n\n /**\n * The request conflicts with the current state of the server.\n */\n CONFLICT = 409,\n\n /**\n * The resource has been permanently deleted with no forwarding address.\n */\n GONE = 410,\n\n /**\n * The server requires a Content-Length header field.\n */\n LENGTH_REQUIRED = 411,\n\n /**\n * Preconditions in the client's headers failed.\n */\n PRECONDITION_FAILED = 412,\n\n /**\n * Request entity is larger than limits defined by server.\n */\n REQUEST_TOO_LONG = 413,\n\n /**\n * The request payload exceeds server size limits.\n * Modern equivalent of REQUEST_TOO_LONG.\n */\n PAYLOAD_TOO_LARGE = 413,\n\n /**\n * The URI requested is too long for the server to interpret.\n */\n REQUEST_URI_TOO_LONG = 414,\n\n /**\n * The server does not support the media type requested by the client.\n */\n UNSUPPORTED_MEDIA_TYPE = 415,\n\n /**\n * The range specified by the Range header cannot be fulfilled.\n */\n REQUESTED_RANGE_NOT_SATISFIABLE = 416,\n\n /**\n * The server cannot meet the expectations given in the Expect header.\n */\n EXPECTATION_FAILED = 417,\n\n /**\n * The server refuses to brew coffee because it is a teapot. (April Fools' joke)\n */\n IM_A_TEAPOT = 418,\n\n /**\n * The server cannot store the representation needed to complete the request.\n */\n INSUFFICIENT_SPACE_ON_RESOURCE = 419,\n\n /**\n * @deprecated\n * A method has failed - specific to Spring Framework.\n */\n METHOD_FAILURE = 420,\n\n /**\n * The server cannot produce a response for the requested URI scheme and authority.\n */\n MISDIRECTED_REQUEST = 421,\n\n /**\n * The request was well-formed but has semantic errors preventing processing.\n */\n UNPROCESSABLE_ENTITY = 422,\n\n /**\n * The requested resource is locked against access.\n */\n LOCKED = 423,\n\n /**\n * The request failed due to the failure of a previous request.\n */\n FAILED_DEPENDENCY = 424,\n\n /**\n * The client should switch to a different protocol.\n */\n UPGRADE_REQUIRED = 426,\n\n /**\n * The server requires conditional requests to prevent lost updates.\n */\n PRECONDITION_REQUIRED = 428,\n\n /**\n * The client has sent too many requests in a given time period (rate limiting).\n */\n TOO_MANY_REQUESTS = 429,\n\n /**\n * Request headers are too large for the server to process.\n */\n REQUEST_HEADER_FIELDS_TOO_LARGE = 431,\n\n /**\n * Resource cannot be legally provided (e.g., censored by government).\n */\n UNAVAILABLE_FOR_LEGAL_REASONS = 451,\n\n // 5xx Server Error\n /**\n * The server encountered an unexpected error preventing it from fulfilling the request.\n */\n INTERNAL_SERVER_ERROR = 500,\n\n /**\n * The server does not support the functionality required to fulfill the request.\n */\n NOT_IMPLEMENTED = 501,\n\n /**\n * The server, acting as a gateway, received an invalid response from an upstream server.\n */\n BAD_GATEWAY = 502,\n\n /**\n * The server is currently unable to handle the request due to temporary overload or maintenance.\n */\n SERVICE_UNAVAILABLE = 503,\n\n /**\n * The server, acting as a gateway, did not receive a timely response from an upstream server.\n */\n GATEWAY_TIMEOUT = 504,\n\n /**\n * The server does not support the HTTP protocol version used in the request.\n */\n HTTP_VERSION_NOT_SUPPORTED = 505,\n\n /**\n * Transparent content negotiation for the request resulted in circular reference.\n */\n VARIANT_ALSO_NEGOTIATES = 506,\n\n /**\n * The server cannot store the representation needed to complete the request.\n */\n INSUFFICIENT_STORAGE = 507,\n\n /**\n * The server detected an infinite loop while processing the request.\n */\n LOOP_DETECTED = 508,\n\n /**\n * Further extensions to the request are required for the server to fulfill it.\n */\n NOT_EXTENDED = 510,\n\n /**\n * The client needs to authenticate to gain network access.\n */\n NETWORK_AUTHENTICATION_REQUIRED = 511,\n}\n"]}
|
|
1
|
+
{"version":3,"file":"http-status-codes.js","s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uDAAU,CAAA;IAEV;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,+EAAsB,CAAA;IAEtB;;;OAGG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,2FAA4B,CAAA;IAE5B;;OAEG;IACH,6GAAqC,CAAA;IAErC;;OAEG;IACH,mFAAwB,CAAA;IAExB;;OAEG;IACH,qEAAiB,CAAA;IAEjB;;OAEG;IACH,2GAAoC,CAAA;IAEpC;;;OAGG;IACH,2EAAoB,CAAA;IAEpB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,2DAAY,CAAA;IAEZ;;OAEG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,+EAAsB,CAAA;IAEtB;;OAEG;IACH,yFAA2B,CAAA;IAE3B;;OAEG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,6GAAqC,CAAA;IAErC;;OAEG;IACH,yGAAmC,CAAA;IAEnC,mBAAmB;IACnB;;OAEG;IACH,yFAA2B,CAAA;IAE3B;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,qEAAiB,CAAA;IAEjB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,mGAAgC,CAAA;IAEhC;;OAEG;IACH,6FAA6B,CAAA;IAE7B;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,yEAAmB,CAAA;IAEnB;;OAEG;IACH,uEAAkB,CAAA;IAElB;;OAEG;IACH,6GAAqC,CAAA;AACvC,CAAC,EAxUW,eAAe,KAAf,eAAe,QAwU1B","sourcesContent":["/**\n * Complete HTTP status codes enum with descriptions.\n * For use with API responses and error handling.\n */\nexport enum HttpStatusCodes {\n // 1xx Informational\n /**\n * The server has received the request headers and the client should proceed to send the request body.\n */\n CONTINUE = 100,\n\n /**\n * The server is switching protocols according to the client's request.\n */\n SWITCHING_PROTOCOLS = 101,\n\n /**\n * Server has received the request and is still processing it.\n */\n PROCESSING = 102,\n\n /**\n * The server is sending preliminary headers while preparing the final response.\n */\n EARLY_HINTS = 103,\n\n // 2xx Success\n /**\n * The request succeeded. The result meaning depends on the HTTP method used.\n */\n OK = 200,\n\n /**\n * The request succeeded and a new resource was created as a result.\n */\n CREATED = 201,\n\n /**\n * The request has been received but not yet acted upon.\n */\n ACCEPTED = 202,\n\n /**\n * The returned information is from a third-party source, not the origin server.\n */\n NON_AUTHORITATIVE_INFORMATION = 203,\n\n /**\n * The request succeeded but there's no content to send in the response.\n */\n NO_CONTENT = 204,\n\n /**\n * The client should reset the document view that caused this request.\n */\n RESET_CONTENT = 205,\n\n /**\n * The server is delivering only part of the resource due to a range header sent by the client.\n */\n PARTIAL_CONTENT = 206,\n\n /**\n * Conveys information about multiple resources, for complex operations.\n */\n MULTI_STATUS = 207,\n\n /**\n * The members of a DAV binding have already been enumerated and are not included in the response.\n */\n ALREADY_REPORTED = 208,\n\n /**\n * The server has fulfilled a request for the resource, and the response represents the result of one or more instance-manipulations.\n */\n IM_USED = 226,\n\n // 3xx Redirection\n /**\n * The request has more than one possible response and the client should choose one.\n */\n MULTIPLE_CHOICES = 300,\n\n /**\n * The resource has been permanently moved to a new URL.\n */\n MOVED_PERMANENTLY = 301,\n\n /**\n * The resource has been temporarily moved to another URL.\n */\n MOVED_TEMPORARILY = 302,\n\n /**\n * The response to the request can be found under another URI using the GET method.\n */\n SEE_OTHER = 303,\n\n /**\n * The resource hasn't been modified since the last request.\n */\n NOT_MODIFIED = 304,\n\n /**\n * @deprecated\n * Response must be accessed through a proxy.\n */\n USE_PROXY = 305,\n\n /**\n * The resource is temporarily available at a different URI, using the same HTTP method.\n */\n TEMPORARY_REDIRECT = 307,\n\n /**\n * The resource has been permanently moved to another URL, using the same HTTP method.\n */\n PERMANENT_REDIRECT = 308,\n\n // 4xx Client Error\n /**\n * The server cannot process the request due to a client error (malformed request).\n */\n BAD_REQUEST = 400,\n\n /**\n * Authentication is required and has failed or not been provided.\n */\n UNAUTHORIZED = 401,\n\n /**\n * Reserved for future use, originally intended for digital payment systems.\n */\n PAYMENT_REQUIRED = 402,\n\n /**\n * The client doesn't have permission to access the requested resource.\n */\n FORBIDDEN = 403,\n\n /**\n * The requested resource could not be found on the server.\n */\n NOT_FOUND = 404,\n\n /**\n * The request method is not supported for the requested resource.\n */\n METHOD_NOT_ALLOWED = 405,\n\n /**\n * The server can't provide a response matching the list of acceptable values in the client's headers.\n */\n NOT_ACCEPTABLE = 406,\n\n /**\n * Authentication by a proxy is required.\n */\n PROXY_AUTHENTICATION_REQUIRED = 407,\n\n /**\n * The server timed out waiting for the request.\n */\n REQUEST_TIMEOUT = 408,\n\n /**\n * The request conflicts with the current state of the server.\n */\n CONFLICT = 409,\n\n /**\n * The resource has been permanently deleted with no forwarding address.\n */\n GONE = 410,\n\n /**\n * The server requires a Content-Length header field.\n */\n LENGTH_REQUIRED = 411,\n\n /**\n * Preconditions in the client's headers failed.\n */\n PRECONDITION_FAILED = 412,\n\n /**\n * Request entity is larger than limits defined by server.\n */\n REQUEST_TOO_LONG = 413,\n\n /**\n * The request payload exceeds server size limits.\n * Modern equivalent of REQUEST_TOO_LONG.\n */\n PAYLOAD_TOO_LARGE = 413,\n\n /**\n * The URI requested is too long for the server to interpret.\n */\n REQUEST_URI_TOO_LONG = 414,\n\n /**\n * The server does not support the media type requested by the client.\n */\n UNSUPPORTED_MEDIA_TYPE = 415,\n\n /**\n * The range specified by the Range header cannot be fulfilled.\n */\n REQUESTED_RANGE_NOT_SATISFIABLE = 416,\n\n /**\n * The server cannot meet the expectations given in the Expect header.\n */\n EXPECTATION_FAILED = 417,\n\n /**\n * The server refuses to brew coffee because it is a teapot. (April Fools' joke)\n */\n IM_A_TEAPOT = 418,\n\n /**\n * The server cannot store the representation needed to complete the request.\n */\n INSUFFICIENT_SPACE_ON_RESOURCE = 419,\n\n /**\n * @deprecated\n * A method has failed - specific to Spring Framework.\n */\n METHOD_FAILURE = 420,\n\n /**\n * The server cannot produce a response for the requested URI scheme and authority.\n */\n MISDIRECTED_REQUEST = 421,\n\n /**\n * The request was well-formed but has semantic errors preventing processing.\n */\n UNPROCESSABLE_ENTITY = 422,\n\n /**\n * The requested resource is locked against access.\n */\n LOCKED = 423,\n\n /**\n * The request failed due to the failure of a previous request.\n */\n FAILED_DEPENDENCY = 424,\n\n /**\n * The client should switch to a different protocol.\n */\n UPGRADE_REQUIRED = 426,\n\n /**\n * The server requires conditional requests to prevent lost updates.\n */\n PRECONDITION_REQUIRED = 428,\n\n /**\n * The client has sent too many requests in a given time period (rate limiting).\n */\n TOO_MANY_REQUESTS = 429,\n\n /**\n * Request headers are too large for the server to process.\n */\n REQUEST_HEADER_FIELDS_TOO_LARGE = 431,\n\n /**\n * Resource cannot be legally provided (e.g., censored by government).\n */\n UNAVAILABLE_FOR_LEGAL_REASONS = 451,\n\n // 5xx Server Error\n /**\n * The server encountered an unexpected error preventing it from fulfilling the request.\n */\n INTERNAL_SERVER_ERROR = 500,\n\n /**\n * The server does not support the functionality required to fulfill the request.\n */\n NOT_IMPLEMENTED = 501,\n\n /**\n * The server, acting as a gateway, received an invalid response from an upstream server.\n */\n BAD_GATEWAY = 502,\n\n /**\n * The server is currently unable to handle the request due to temporary overload or maintenance.\n */\n SERVICE_UNAVAILABLE = 503,\n\n /**\n * The server, acting as a gateway, did not receive a timely response from an upstream server.\n */\n GATEWAY_TIMEOUT = 504,\n\n /**\n * The server does not support the HTTP protocol version used in the request.\n */\n HTTP_VERSION_NOT_SUPPORTED = 505,\n\n /**\n * Transparent content negotiation for the request resulted in circular reference.\n */\n VARIANT_ALSO_NEGOTIATES = 506,\n\n /**\n * The server cannot store the representation needed to complete the request.\n */\n INSUFFICIENT_STORAGE = 507,\n\n /**\n * The server detected an infinite loop while processing the request.\n */\n LOOP_DETECTED = 508,\n\n /**\n * Further extensions to the request are required for the server to fulfill it.\n */\n NOT_EXTENDED = 510,\n\n /**\n * The client needs to authenticate to gain network access.\n */\n NETWORK_AUTHENTICATION_REQUIRED = 511\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomUUID, randomBytes } from
|
|
1
|
+
import { randomUUID, randomBytes } from 'crypto';
|
|
2
2
|
/**
|
|
3
3
|
* Generates a UUID v4 string (RFC 4122).
|
|
4
4
|
*
|
|
@@ -15,12 +15,12 @@ export function uuid() {
|
|
|
15
15
|
*/
|
|
16
16
|
export function nanoId(length = 21) {
|
|
17
17
|
if (length <= 0)
|
|
18
|
-
return
|
|
19
|
-
let id =
|
|
18
|
+
return '';
|
|
19
|
+
let id = '';
|
|
20
20
|
while (id.length < length) {
|
|
21
21
|
id += randomBytes(Math.ceil((length * 3) / 4))
|
|
22
|
-
.toString(
|
|
23
|
-
.replace(/[+/=]/g,
|
|
22
|
+
.toString('base64url')
|
|
23
|
+
.replace(/[+/=]/g, '');
|
|
24
24
|
}
|
|
25
25
|
return id.slice(0, length);
|
|
26
26
|
}
|
|
@@ -34,8 +34,8 @@ export function randomHex(byteLength = 16) {
|
|
|
34
34
|
// Use Node.js crypto for both Node and browser compatibility
|
|
35
35
|
// Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)
|
|
36
36
|
return randomBytes(byteLength)
|
|
37
|
-
.toString(
|
|
38
|
-
.padStart(byteLength * 2,
|
|
37
|
+
.toString('hex')
|
|
38
|
+
.padStart(byteLength * 2, '0')
|
|
39
39
|
.slice(0, byteLength * 2);
|
|
40
40
|
}
|
|
41
41
|
/**
|
|
@@ -56,6 +56,6 @@ export function randomInt(min, max) {
|
|
|
56
56
|
* @returns {string} Random base64 string (URL-safe, no padding).
|
|
57
57
|
*/
|
|
58
58
|
export function randomBase64(byteLength = 16) {
|
|
59
|
-
return randomBytes(byteLength).toString(
|
|
59
|
+
return randomBytes(byteLength).toString('base64url');
|
|
60
60
|
}
|
|
61
61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GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,aAAqB,EAAE;IAClD,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import { randomUUID, randomBytes } from
|
|
1
|
+
{"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAEjD;;;;GAIG;AACH,MAAM,UAAU,IAAI;IAClB,OAAO,UAAU,EAAE,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,SAAiB,EAAE;IACxC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC3B,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,OAAO,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;QAC1B,EAAE,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;aAC3C,QAAQ,CAAC,WAAW,CAAC;aACrB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,aAAqB,EAAE;IAC/C,6DAA6D;IAC7D,kGAAkG;IAClG,OAAO,WAAW,CAAC,UAAU,CAAC;SAC3B,QAAQ,CAAC,KAAK,CAAC;SACf,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,GAAG,CAAC;SAC7B,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW,EAAE,GAAW;IAChD,MAAM,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,aAAqB,EAAE;IAClD,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import { randomUUID, randomBytes } from 'crypto';\n\n/**\n * Generates a UUID v4 string (RFC 4122).\n *\n * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')\n */\nexport function uuid(): string {\n return randomUUID();\n}\n\n/**\n * Generates a nanoid-style random ID (URL-safe, customizable length).\n *\n * @param {number} length - Length of the ID (default: 21).\n * @returns {string} Nanoid-style random string.\n */\nexport function nanoId(length: number = 21): string {\n if (length <= 0) return '';\n let id = '';\n while (id.length < length) {\n id += randomBytes(Math.ceil((length * 3) / 4))\n .toString('base64url')\n .replace(/[+/=]/g, '');\n }\n return id.slice(0, length);\n}\n\n/**\n * Generates a cryptographically strong random hex string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).\n * @returns {string} Random hex string.\n */\nexport function randomHex(byteLength: number = 16): string {\n // Use Node.js crypto for both Node and browser compatibility\n // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)\n return randomBytes(byteLength)\n .toString('hex')\n .padStart(byteLength * 2, '0')\n .slice(0, byteLength * 2);\n}\n\n/**\n * Generates a random integer between min (inclusive) and max (inclusive).\n *\n * @param {number} min - Minimum value.\n * @param {number} max - Maximum value.\n * @returns {number} Random integer in range.\n */\nexport function randomInt(min: number, max: number): number {\n const range = max - min + 1;\n return Math.floor(Math.random() * range) + min;\n}\n\n/**\n * Generates a cryptographically strong random base64 string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16).\n * @returns {string} Random base64 string (URL-safe, no padding).\n */\nexport function randomBase64(byteLength: number = 16): string {\n return randomBytes(byteLength).toString('base64url');\n}\n"]}
|
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
import
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
import type { Logger as PinoLogger } from 'pino';
|
|
3
|
+
/**
|
|
4
|
+
* Logger type for application-wide logging.
|
|
5
|
+
*/
|
|
6
|
+
export type Logger = pino.Logger;
|
|
7
|
+
/**
|
|
8
|
+
* Logger levels for application-wide logging.
|
|
9
|
+
*/
|
|
10
|
+
export type LoggerLevels = pino.Level;
|
|
2
11
|
/**
|
|
3
12
|
* Use an object compatible with either modern or legacy global scopes.
|
|
4
13
|
*/
|
|
@@ -11,7 +20,7 @@ export declare const _globalThis: typeof globalThis;
|
|
|
11
20
|
*
|
|
12
21
|
* @returns {Logger} The logger instance (request-bound or global root logger)
|
|
13
22
|
*/
|
|
14
|
-
export declare function getLogger():
|
|
23
|
+
export declare function getLogger(): PinoLogger;
|
|
15
24
|
/**
|
|
16
25
|
* Creates a child logger with additional context.
|
|
17
26
|
*
|
|
@@ -19,7 +28,7 @@ export declare function getLogger(): Logger;
|
|
|
19
28
|
* @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
|
|
20
29
|
* @returns {Logger} Child logger with merged context
|
|
21
30
|
*/
|
|
22
|
-
export declare function createChildLogger(bindings: Record<string, any>, parentLogger?:
|
|
31
|
+
export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
|
|
23
32
|
/**
|
|
24
33
|
* Creates a request-scoped logger with request ID and stores it in context
|
|
25
34
|
*
|
|
@@ -27,7 +36,7 @@ export declare function createChildLogger(bindings: Record<string, any>, parentL
|
|
|
27
36
|
* @param {object} [additionalContext] - Additional context to include in logs
|
|
28
37
|
* @returns {Logger} Request-scoped logger instance
|
|
29
38
|
*/
|
|
30
|
-
export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>):
|
|
39
|
+
export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
|
|
31
40
|
/**
|
|
32
41
|
* Utility to safely log errors with proper stack trace extraction
|
|
33
42
|
*
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import pino, { stdTimeFunctions } from
|
|
2
|
-
import { Config } from
|
|
3
|
-
import { ContextStore, StoreKeys } from
|
|
1
|
+
import pino, { stdTimeFunctions } from 'pino';
|
|
2
|
+
import { Config } from '../config';
|
|
3
|
+
import { ContextStore, StoreKeys } from './context-store.utils';
|
|
4
4
|
/**
|
|
5
5
|
* Symbol used to store the root logger in the Node.js global object.
|
|
6
6
|
*/
|
|
7
|
-
const GLOBAL_LOGGER_KEY = Symbol.for(
|
|
7
|
+
const GLOBAL_LOGGER_KEY = Symbol.for('logger');
|
|
8
8
|
/**
|
|
9
9
|
* Use an object compatible with either modern or legacy global scopes.
|
|
10
10
|
*/
|
|
11
|
-
export const _globalThis = typeof globalThis ===
|
|
11
|
+
export const _globalThis = typeof globalThis === 'object' ? globalThis : global;
|
|
12
12
|
const _global = _globalThis;
|
|
13
13
|
/**
|
|
14
14
|
* Initializes the global root logger according to app configuration.
|
|
@@ -21,23 +21,21 @@ function setupLogger() {
|
|
|
21
21
|
name: Config.Logger.name,
|
|
22
22
|
level: Config.Logger.level,
|
|
23
23
|
redact: {
|
|
24
|
-
paths: [
|
|
24
|
+
paths: ['req.authorization', 'url'],
|
|
25
25
|
censor(value, path) {
|
|
26
|
-
if (path[0] ===
|
|
27
|
-
return value.replace(/access_token=[a-zA-Z0-9_-]*/,
|
|
26
|
+
if (path[0] === 'url') {
|
|
27
|
+
return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');
|
|
28
28
|
}
|
|
29
|
-
else if (path[1] ===
|
|
30
|
-
return value.replace(/\s+(\S+)$/,
|
|
29
|
+
else if (path[1] === 'authorization') {
|
|
30
|
+
return value.replace(/\s+(\S+)$/, ' ***');
|
|
31
31
|
}
|
|
32
|
-
return
|
|
33
|
-
}
|
|
32
|
+
return '***';
|
|
33
|
+
}
|
|
34
34
|
},
|
|
35
|
+
timestamp: stdTimeFunctions.isoTime
|
|
35
36
|
};
|
|
36
|
-
if (Config.Logger.isoTimestamp) {
|
|
37
|
-
logParams.timestamp = stdTimeFunctions.isoTime;
|
|
38
|
-
}
|
|
39
37
|
_global[GLOBAL_LOGGER_KEY] = pino(logParams);
|
|
40
|
-
_global[GLOBAL_LOGGER_KEY].debug(
|
|
38
|
+
_global[GLOBAL_LOGGER_KEY].debug('Logger initialized');
|
|
41
39
|
}
|
|
42
40
|
/**
|
|
43
41
|
* Retrieves the current logger instance:
|
|
@@ -81,7 +79,7 @@ export function createRequestLogger(requestId, additionalContext = {}) {
|
|
|
81
79
|
}
|
|
82
80
|
catch (_a) {
|
|
83
81
|
// Context not initialized, can't store logger
|
|
84
|
-
logger.debug(
|
|
82
|
+
logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
|
|
85
83
|
}
|
|
86
84
|
return logger;
|
|
87
85
|
}
|
|
@@ -95,7 +93,7 @@ export function createRequestLogger(requestId, additionalContext = {}) {
|
|
|
95
93
|
export function logError(error, message, context) {
|
|
96
94
|
const logger = getLogger();
|
|
97
95
|
const errObj = error instanceof Error ? error : new Error(String(error));
|
|
98
|
-
const logContext = Object.assign(Object.assign({}, context), {
|
|
96
|
+
const logContext = Object.assign(Object.assign({}, context), { error: errObj });
|
|
99
97
|
logger.error(logContext, message || errObj.message);
|
|
100
98
|
}
|
|
101
99
|
//# sourceMappingURL=logger.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAA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AM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,MAAM,UAAU,mCACX,OAAO,KACV,KAAK,EAAE,MAAM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { Config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: Config.Logger.name,\n level: Config.Logger.level,\n redact: {\n paths: ['req.authorization', 'url'],\n censor(value, path) {\n if (path[0] === 'url') {\n return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');\n } else if (path[1] === 'authorization') {\n return value.replace(/\\s+(\\S+)$/, ' ***');\n }\n return '***';\n }\n },\n timestamp: stdTimeFunctions.isoTime\n };\n\n _global[GLOBAL_LOGGER_KEY] = pino(logParams);\n _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
|