arkos 1.3.5-beta → 1.3.5-canary.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/cjs/app.js.map +1 -1
  2. package/dist/cjs/modules/auth/auth.router.js +9 -0
  3. package/dist/cjs/modules/auth/auth.router.js.map +1 -1
  4. package/dist/cjs/modules/error-handler/error-handler.controller.js +3 -9
  5. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  6. package/dist/cjs/modules/error-handler/utils/app-error.js +12 -3
  7. package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
  8. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  9. package/dist/cjs/modules/file-upload/file-upload.router.js +10 -2
  10. package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
  11. package/dist/cjs/utils/cli/dev.js.map +1 -1
  12. package/dist/cjs/utils/cli/start.js +1 -2
  13. package/dist/cjs/utils/cli/start.js.map +1 -1
  14. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  15. package/dist/esm/app.js.map +1 -1
  16. package/dist/esm/modules/auth/auth.router.js +10 -1
  17. package/dist/esm/modules/auth/auth.router.js.map +1 -1
  18. package/dist/esm/modules/error-handler/error-handler.controller.js +3 -6
  19. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  20. package/dist/esm/modules/error-handler/utils/app-error.js +12 -3
  21. package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
  22. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  23. package/dist/esm/modules/file-upload/file-upload.router.js +10 -2
  24. package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
  25. package/dist/esm/utils/cli/dev.js.map +1 -1
  26. package/dist/esm/utils/cli/start.js +1 -2
  27. package/dist/esm/utils/cli/start.js.map +1 -1
  28. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  29. package/dist/types/modules/error-handler/utils/app-error.d.ts +1 -1
  30. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,8BAmLC;AA5MD,mDAA0C;AAC1C,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAAkE;AAClE,iFAA+E;AAE/E,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AACpE,2DAAiE;AACjE,2DAAmD;AACnD,2FAAkE;AAErD,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAC9C,MAAM,iBAAiB,GAAG,IAAA,gBAAM,GAAE,CAAC;AAE5B,KAAK,UAAU,SAAS,CAC7B,WAAwB;IAExB,MAAM,OAAO,CAAC,GAAG,CAAC;QAChB,IAAA,iCAAgB,GAAE;QAClB,IAAA,wCAAuB,EAAC,WAAW,CAAC;QACpC,WAAW,EAAE,YAAY,IAAI,CAAC,MAAM,WAAW,EAAE,YAAY,CAAC,WAAG,CAAC,CAAC;KACpE,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAG,WAAW,EAAE,WAAW,CAAC;IACnD,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE,CAAC;IAC7D,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE,CAAC;IAE7D,WAAG,CAAC,GAAG,CAAC,0BAAe,CAAC,oBAAoB,CAAC,CAAC;IAE9C,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,aAAa,CAAC;QACjD,WAAG,CAAC,GAAG,CACL,mBAAmB,CAAC,WAAW;YAC7B,IAAA,qBAAW,EAAC,WAAW,EAAE,kBAAkB,CAAC,CAC/C,CAAC;IAEJ,IAAI,CAAC,mBAAmB,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sBAAsB,CAAC;QAC1D,WAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,kCAAY,CAAC,CAAC;IAElE,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\n\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n arkosConfig?.configureApp && (await arkosConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n app.use(debuggerService.logLevel2RequestInfo);\n\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n }\n\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n }\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.route },\n \"RouteNotFound\"\n );\n });\n\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,8BAm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";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\n\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n arkosConfig?.configureApp && (await arkosConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n app.use(debuggerService.logLevel2RequestInfo);\n\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n }\n\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n }\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.route },\n \"RouteNotFound\"\n );\n });\n\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
@@ -14,10 +14,19 @@ const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerg
14
14
  const routers_helpers_1 = require("../../utils/helpers/routers.helpers");
15
15
  const base_router_helpers_1 = require("../base/utils/helpers/base.router.helpers");
16
16
  const debugger_service_1 = __importDefault(require("../debugger/debugger.service"));
17
+ const router_validator_1 = __importDefault(require("../base/utils/router-validator"));
18
+ const fs_helpers_1 = require("../../utils/helpers/fs.helpers");
17
19
  const router = (0, express_1.Router)();
18
20
  async function getAuthRouter(arkosConfigs) {
19
21
  const { interceptors, dtos, schemas, prismaQueryOptions, router: customRouterModule, } = (0, dynamic_loader_1.getModuleComponents)("auth") || {};
20
22
  const routerConfig = customRouterModule?.config || {};
23
+ const customRouter = customRouterModule?.default;
24
+ if (customRouter && customRouterModule) {
25
+ if (router_validator_1.default.isExpressRouter(customRouter))
26
+ router.use(`/auth`, customRouter);
27
+ else
28
+ throw Error(`ValidationError: The exported router from auth.router.${(0, fs_helpers_1.getUserFileExtension)()} is not a valid express Router.`);
29
+ }
21
30
  const authController = await (0, auth_controller_1.authControllerFactory)(interceptors);
22
31
  if (routerConfig?.disable === true)
23
32
  return router;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":";;;;;AAsBA,sCA2MC;AAjOD,qCAAiC;AACjC,uDAA0D;AAC1D,kEAAyC;AACzC,4EAA2C;AAC3C,+DAGoC;AACpC,+DAIkC;AAElC,4FAA6D;AAE7D,yEAAwE;AACxE,mFAA+E;AAC/E,oFAA2D;AAE3D,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,aAAa,CAAC,YAAyB;IAC3D,MAAM,EACJ,YAAY,EACZ,IAAI,EACJ,OAAO,EACP,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,GAC3B,GAAG,IAAA,oCAAmB,EAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAEtC,MAAM,YAAY,GAAG,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;IACtD,MAAM,cAAc,GAAG,MAAM,IAAA,uCAAqB,EAAC,YAAY,CAAC,CAAC;IAEjE,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAElD,MAAM,wBAAwB,GAAG,CAC/B,GAAuD,EACvD,EAAE;QACF,MAAM,iBAAiB,GAAG,YAAY,EAAE,UAAU,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C,EACtD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,cAAc,CAAC,iBAAiB,EAChC,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,sBAAsB,CAAC,EAC1D,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,wBAAwB,EAAE;YAC3D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IAEJ,0BAAe,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport {\n getModuleComponents,\n ModuleComponents,\n} from \"../../utils/dynamic-loader\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const {\n interceptors,\n dtos,\n schemas,\n prismaQueryOptions,\n router: customRouterModule,\n } = getModuleComponents(\"auth\") || {};\n\n const routerConfig = customRouterModule?.config || {};\n const authController = await authControllerFactory(interceptors);\n\n if (routerConfig?.disable === true) return router;\n\n const getValidationSchemaOrDto = (\n key: \"updateMe\" | \"updatePassword\" | \"login\" | \"signup\"\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n if (!isEndpointDisabled(routerConfig, \"getMe\")) {\n router.get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...processMiddleware(interceptors?.beforeGetMe),\n authController.getMe,\n ...processMiddleware(interceptors?.afterGetMe),\n sendResponse,\n ...processMiddleware(interceptors?.onGetMeError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateMe\")) {\n router.patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMe),\n authController.updateMe,\n ...processMiddleware(interceptors?.afterUpdateMe),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateMeError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteMe\")) {\n router.delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMe),\n authController.deleteMe,\n ...processMiddleware(interceptors?.afterDeleteMe),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteMeError, { type: \"error\" })\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"login\") ||\n !isEndpointDisabled(routerConfig, \"logout\") ||\n !isEndpointDisabled(routerConfig, \"signup\") ||\n !isEndpointDisabled(routerConfig, \"updatePassword\")\n ) {\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"login\")) {\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...processMiddleware(interceptors?.beforeLogin),\n authController.login,\n ...processMiddleware(interceptors?.afterLogin),\n sendResponse,\n ...processMiddleware(interceptors?.onLoginError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"logout\")) {\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n ...processMiddleware(interceptors?.beforeLogout),\n authController.logout,\n ...processMiddleware(interceptors?.afterLogout),\n sendResponse,\n ...processMiddleware(interceptors?.onLogoutError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"signup\")) {\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...processMiddleware(interceptors?.beforeSignup),\n authController.signup,\n ...processMiddleware(interceptors?.afterSignup),\n sendResponse,\n ...processMiddleware(interceptors?.onSignupError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updatePassword\")) {\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...processMiddleware(interceptors?.beforeUpdatePassword),\n authController.updatePassword,\n ...processMiddleware(interceptors?.afterUpdatePassword),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdatePasswordError, {\n type: \"error\",\n })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"findManyAuthAction\"))\n router.get(\n \"/auth-actions\",\n authService.authenticate,\n authService.handleAccessControl(\"View\", \"auth-action\"),\n ...processMiddleware(interceptors?.beforeFindManyAuthAction),\n authController.findManyAuthAction,\n ...processMiddleware(interceptors?.afterFindManyAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyAuthActionError, {\n type: \"error\",\n })\n );\n\n if (!isEndpointDisabled(routerConfig, \"findOneAuthAction\"))\n router.get(\n \"/auth-actions/:resourceName\",\n authService.authenticate,\n authService.handleAccessControl(\"View\", \"auth-action\"),\n ...processMiddleware(interceptors?.beforeFindOneAuthAction),\n authController.findOneAuthAction,\n ...processMiddleware(interceptors?.afterFindOneAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneAuthActionError, {\n type: \"error\",\n })\n );\n\n debuggerService.logModuleFinalRouter(\"auth\", router);\n return router;\n}\n"]}
1
+ {"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":";;;;;AAqBA,sCAsNC;AA3OD,qCAAiC;AACjC,uDAA0D;AAC1D,kEAAyC;AACzC,4EAA2C;AAC3C,+DAAiE;AACjE,+DAIkC;AAElC,4FAA6D;AAE7D,yEAAwE;AACxE,mFAA+E;AAC/E,oFAA2D;AAC3D,sFAA6D;AAC7D,+DAAsE;AAEtE,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,aAAa,CAAC,YAAyB;IAC3D,MAAM,EACJ,YAAY,EACZ,IAAI,EACJ,OAAO,EACP,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,GAC3B,GAAG,IAAA,oCAAmB,EAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAEtC,MAAM,YAAY,GAAG,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;IACtD,MAAM,YAAY,GAAG,kBAAkB,EAAE,OAAiB,CAAC;IAE3D,IAAI,YAAY,IAAI,kBAAkB,EAAE,CAAC;QACvC,IA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AAY,EAAE,wBAAwB,CAAC,EAC5D,cAAc,CAAC,kBAAkB,EACjC,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,yBAAyB,EAAE;YAC5D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IAEJ,IAAI,CAAC,IAAA,wCAAkB,EAAC,YAAY,EAAE,mBAAmB,CAAC;QACxD,MAAM,CAAC,GAAG,CACR,6BAA6B,EAC7B,sBAAW,CAAC,YAAY,EACxB,sBAAW,CAAC,mBAAmB,CAAC,MAAM,EAAE,aAAa,CAAC,EACtD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,cAAc,CAAC,iBAAiB,EAChC,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,sBAAsB,CAAC,EAC1D,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,wBAAwB,EAAE;YAC3D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IAEJ,0BAAe,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const {\n interceptors,\n dtos,\n schemas,\n prismaQueryOptions,\n router: customRouterModule,\n } = getModuleComponents(\"auth\") || {};\n\n const routerConfig = customRouterModule?.config || {};\n const customRouter = customRouterModule?.default as Router;\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/auth`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from auth.router.${getUserFileExtension()} is not a valid express Router.`\n );\n }\n\n const authController = await authControllerFactory(interceptors);\n\n if (routerConfig?.disable === true) return router;\n\n const getValidationSchemaOrDto = (\n key: \"updateMe\" | \"updatePassword\" | \"login\" | \"signup\"\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n if (!isEndpointDisabled(routerConfig, \"getMe\")) {\n router.get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...processMiddleware(interceptors?.beforeGetMe),\n authController.getMe,\n ...processMiddleware(interceptors?.afterGetMe),\n sendResponse,\n ...processMiddleware(interceptors?.onGetMeError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateMe\")) {\n router.patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMe),\n authController.updateMe,\n ...processMiddleware(interceptors?.afterUpdateMe),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateMeError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteMe\")) {\n router.delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMe),\n authController.deleteMe,\n ...processMiddleware(interceptors?.afterDeleteMe),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteMeError, { type: \"error\" })\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"login\") ||\n !isEndpointDisabled(routerConfig, \"logout\") ||\n !isEndpointDisabled(routerConfig, \"signup\") ||\n !isEndpointDisabled(routerConfig, \"updatePassword\")\n ) {\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"login\")) {\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...processMiddleware(interceptors?.beforeLogin),\n authController.login,\n ...processMiddleware(interceptors?.afterLogin),\n sendResponse,\n ...processMiddleware(interceptors?.onLoginError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"logout\")) {\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n ...processMiddleware(interceptors?.beforeLogout),\n authController.logout,\n ...processMiddleware(interceptors?.afterLogout),\n sendResponse,\n ...processMiddleware(interceptors?.onLogoutError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"signup\")) {\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...processMiddleware(interceptors?.beforeSignup),\n authController.signup,\n ...processMiddleware(interceptors?.afterSignup),\n sendResponse,\n ...processMiddleware(interceptors?.onSignupError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updatePassword\")) {\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...processMiddleware(interceptors?.beforeUpdatePassword),\n authController.updatePassword,\n ...processMiddleware(interceptors?.afterUpdatePassword),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdatePasswordError, {\n type: \"error\",\n })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"findManyAuthAction\"))\n router.get(\n \"/auth-actions\",\n authService.authenticate,\n authService.handleAccessControl(\"View\", \"auth-action\"),\n ...processMiddleware(interceptors?.beforeFindManyAuthAction),\n authController.findManyAuthAction,\n ...processMiddleware(interceptors?.afterFindManyAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyAuthActionError, {\n type: \"error\",\n })\n );\n\n if (!isEndpointDisabled(routerConfig, \"findOneAuthAction\"))\n router.get(\n \"/auth-actions/:resourceName\",\n authService.authenticate,\n authService.handleAccessControl(\"View\", \"auth-action\"),\n ...processMiddleware(interceptors?.beforeFindOneAuthAction),\n authController.findOneAuthAction,\n ...processMiddleware(interceptors?.afterFindOneAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneAuthActionError, {\n type: \"error\",\n })\n );\n\n debuggerService.logModuleFinalRouter(\"auth\", router);\n return router;\n}\n"]}
@@ -32,20 +32,14 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
35
  Object.defineProperty(exports, "__esModule", { value: true });
39
36
  exports.default = errorHandler;
40
- const app_error_1 = __importDefault(require("./utils/app-error"));
41
37
  const errorControllerHelper = __importStar(require("./utils/error-handler.helpers"));
42
38
  const server_1 = require("../../server");
43
39
  function errorHandler(err, req, res, _) {
44
40
  console.error("[\x1b[31mError\x1b[0m]:", err);
45
41
  err.statusCode = err.statusCode || 500;
46
42
  err.status = err.status || "error";
47
- if (process.env.NODE_ENV !== "production")
48
- return sendDevelopmentError(err, req, res);
49
43
  let error = { ...err, message: err.message };
50
44
  if (err.name === "JsonWebTokenError")
51
45
  error = errorControllerHelper.handleJWTError();
@@ -85,8 +79,8 @@ function errorHandler(err, req, res, _) {
85
79
  error = errorControllerHelper.handleVersionMismatchError(err);
86
80
  if (err.name === "NetworkError")
87
81
  error = errorControllerHelper.handleNetworkError(err);
88
- if (!error.isOperational)
89
- error = new app_error_1.default("Internal server error", 500);
82
+ if (process.env.NODE_ENV !== "production")
83
+ return sendDevelopmentError(err, req, res);
90
84
  sendProductionError(error, req, res);
91
85
  }
92
86
  function sendDevelopmentError(err, req, res) {
@@ -109,7 +103,7 @@ function sendProductionError(err, req, res) {
109
103
  status: err.status,
110
104
  message: err.message,
111
105
  meta: err.meta || {},
112
- code: err.code || "unknown",
106
+ code: err.code || "Unknown",
113
107
  });
114
108
  else
115
109
  res.status(500).json({
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAkEC;AArFD,kEAAyC;AACzC,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAA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I,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,uBAAuB;aACjC,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(err, req, res);\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n if (!error.isOperational) error = new AppError(\"Internal server error\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BA6DC;AA/ED,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;IAE7C,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAGnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GA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,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error = { ...err, message: err.message };\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(err, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -1,14 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  class AppError extends Error {
4
- constructor(message, statusCode, meta, code) {
4
+ constructor(message, statusCode, code, meta) {
5
5
  super(message);
6
+ this.code = "Unknown";
6
7
  this.message = message || "An error occurred, try again!";
7
8
  this.statusCode = statusCode;
8
9
  this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
9
10
  this.isOperational = true;
10
- this.code = code || "Unknown";
11
- this.meta = meta;
11
+ if (code && meta && typeof code === typeof meta)
12
+ throw new AppError(`meta and code must not both be ${typeof code}, one must be of type object and other string. but received ${JSON.stringify({ meta, code })}`, 500, "AppErrorMisuse", { meta, code });
13
+ if (typeof code === "string")
14
+ this.code = code || "Unknown";
15
+ if (typeof code === "object")
16
+ this.meta = code;
17
+ if (typeof meta === "string")
18
+ this.code = meta || "Unknown";
19
+ if (typeof meta === "object")
20
+ this.meta = meta;
12
21
  this.missing = false;
13
22
  Error.captureStackTrace(this, this.constructor);
14
23
  }
@@ -1 +1 @@
1
- {"version":3,"file":"app-error.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/app-error.ts"],"names":[],"mappings":";;AAgCA,MAAM,QAAS,SAAQ,KAAK;IAgB1B,YACE,OAAe,EACf,UAAkB,EAClB,IAA0B,EAC1B,IAAa;QAEb,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,+BAA+B,CAAC;QAC1D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,GAAG,UAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;QACjE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QAErB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;CACF;AAED,kBAAe,QAAQ,CAAC","sourcesContent":["/**\n * Custom error class for handling application errors.\n *\n * @extends {Error}\n *\n * @property {number} statusCode - HTTP status code of the error.\n * @property {string} status - Status message derived from the status code (`fail` for 4xx, `error` for 5xx).\n * @property {boolean} [missing=false] - Flag to indicate if a resource is missing.\n * @property {boolean} isOperational - Indicates if the error is operational (intended for client visibility).\n * @property {string} [code] - Optional error code for categorization.\n * @property {Record<string, any>} [meta] - Additional metadata related to the error.\n *\n * @example\n * ```typescript\n *\n * function getUser(id: string) {\n * if (!id) {\n * throw new AppError('User ID is required', 400, { field: 'id' }, 'USER_ID_MISSING');\n * }\n * // Simulate a user not found scenario\n * throw new AppError('User not found', 404, { userId: id }, 'USER_NOT_FOUND');\n * }\n *\n * try {\n * getUser('');\n * } catch (error) {\n * if (error instanceof AppError) {\n * console.error(`Error: ${error.message}, Code: ${error.code}, Status: ${error.status}`);\n * }\n * }\n * ```\n */\nclass AppError extends Error {\n statusCode: number;\n status: string;\n public missing?: boolean;\n public isOperational: boolean;\n code?: string;\n meta?: Record<string, any>;\n\n /**\n * Creates an instance of AppError.\n *\n * @param {string} message - The error message.\n * @param {number} statusCode - The HTTP status code.\n * @param {Record<string, any>} [meta] - Additional metadata for debugging or client feedback.\n * @param {string} [code] - A custom error code for categorization.\n */\n constructor(\n message: string,\n statusCode: number,\n meta?: Record<string, any>,\n code?: string\n ) {\n super(message);\n\n this.message = message || \"An error occurred, try again!\";\n this.statusCode = statusCode;\n this.status = `${statusCode}`.startsWith(\"4\") ? \"fail\" : \"error\";\n this.isOperational = true;\n this.code = code || \"Unknown\";\n this.meta = meta;\n this.missing = false;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\nexport default AppError;\n"]}
1
+ {"version":3,"file":"app-error.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/app-error.ts"],"names":[],"mappings":";;AAgCA,MAAM,QAAS,SAAQ,KAAK;IAgB1B,YACE,OAAe,EACf,UAAkB,EAClB,IAAmC,EACnC,IAAmC;QAEnC,KAAK,CAAC,OAAO,CAAC,CAAC;QAjBjB,SAAI,GAAY,SAAS,CAAC;QAmBxB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,+BAA+B,CAAC;QAC1D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,GAAG,UAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;QACjE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAE1B,IAAI,IAAI,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,OAAO,IAAI;YAC7C,MAAM,IAAI,QAAQ,CAChB,kCAAkC,OAAO,IAAI,+DAA+D,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,EAC5I,GAAG,EACH,gBAAgB,EAChB,EAAE,IAAI,EAAE,IAAI,EAAE,CACf,CAAC;QAEJ,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC;QAC5D,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAC/C,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC;QAC5D,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAC/C,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QAErB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;CACF;AAED,kBAAe,QAAQ,CAAC","sourcesContent":["/**\n * Custom error class for handling application errors.\n *\n * @extends {Error}\n *\n * @property {number} statusCode - HTTP status code of the error.\n * @property {string} status - Status message derived from the status code (`fail` for 4xx, `error` for 5xx).\n * @property {boolean} [missing=false] - Flag to indicate if a resource is missing.\n * @property {boolean} isOperational - Indicates if the error is operational (intended for client visibility).\n * @property {string} [code] - Optional error code for categorization.\n * @property {Record<string, any>} [meta] - Additional metadata related to the error.\n *\n * @example\n * ```typescript\n *\n * function getUser(id: string) {\n * if (!id) {\n * throw new AppError('User ID is required', 400, 'UserIDMissing', { field: 'id' });\n * }\n * // Simulate a user not found scenario\n * throw new AppError('User not found', 404, 'UserNotFound', { userId: id });\n * }\n *\n * try {\n * getUser('');\n * } catch (error) {\n * if (error instanceof AppError) {\n * console.error(`Error: ${error.message}, Code: ${error.code}, Status: ${error.status}`);\n * }\n * }\n * ```\n */\nclass AppError extends Error {\n statusCode: number;\n status: string;\n public missing?: boolean;\n public isOperational: boolean;\n code?: string = \"Unknown\";\n meta?: Record<string, any>;\n\n /**\n * Creates an instance of AppError.\n *\n * @param {string} message - The error message.\n * @param {number} statusCode - The HTTP status code.\n * @param {Record<string, any>} [meta] - Additional metadata for debugging or client feedback.\n * @param {string} [code] - A custom error code for categorization.\n */\n constructor(\n message: string,\n statusCode: number,\n code?: string | Record<string, any>,\n meta?: Record<string, any> | string\n ) {\n super(message);\n\n this.message = message || \"An error occurred, try again!\";\n this.statusCode = statusCode;\n this.status = `${statusCode}`.startsWith(\"4\") ? \"fail\" : \"error\";\n this.isOperational = true;\n\n if (code && meta && typeof code === typeof meta)\n throw new AppError(\n `meta and code must not both be ${typeof code}, one must be of type object and other string. but received ${JSON.stringify({ meta, code })}`,\n 500,\n \"AppErrorMisuse\",\n { meta, code }\n );\n\n if (typeof code === \"string\") this.code = code || \"Unknown\";\n if (typeof code === \"object\") this.meta = code;\n if (typeof meta === \"string\") this.code = meta || \"Unknown\";\n if (typeof meta === \"object\") this.meta = meta;\n this.missing = false;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\nexport default AppError;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AASA,wCAEC;AAED,4CAEC;AAED,8EAIC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;A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C,GAAa;IAC/C,MAAM,KAAK,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,eAAe,CAAC;IAClD,MAAM,YAAY,GAAG,GAAG,EAAE,IAAI,EAAE,aAAa,IAAI,cAAc,CAAC;IAChE,MAAM,OAAO,GAAG,gCAAgC,KAAK,qBAAqB,YAAY,GAAG,CAAC;IAC1F,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,sBAAsB,CAAC,CAAW;IAChD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,uBAAuB,CAAC,GAGvC;IACC,MAAM,OAAO,GACX,GAAG,EAAE,IAAI,EAAE,KAAK;QAChB,uEAAuE,CAAC;IAC1E,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,gBAAgB,CAAC,CAAC;AACtE,CAAC;AAED,SAAgB,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,mBAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,EAAE,EACF,sBAAsB,CACvB,CAAC;AACJ,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string; // Prisma-specific error code\n message: string; // Error message\n meta?: Record<string, any>; // Metadata provided by Prisma\n name?: string; // Error name\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"RecordNotFound\");\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
1
+ {"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts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Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"RecordNotFound\");\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
@@ -16,21 +16,29 @@ const routers_helpers_1 = require("../../utils/helpers/routers.helpers");
16
16
  const file_upload_helpers_1 = require("./utils/helpers/file-upload.helpers");
17
17
  const base_router_helpers_1 = require("../base/utils/helpers/base.router.helpers");
18
18
  const debugger_service_1 = __importDefault(require("../debugger/debugger.service"));
19
+ const router_validator_1 = __importDefault(require("../base/utils/router-validator"));
20
+ const fs_helpers_1 = require("../../utils/helpers/fs.helpers");
19
21
  const router = (0, express_1.Router)();
20
22
  async function getFileUploadRouter(arkosConfig) {
21
23
  const { fileUpload } = arkosConfig;
22
24
  const moduleComponents = (0, dynamic_loader_1.getModuleComponents)("file-upload");
23
25
  let { interceptors = {}, authConfigs = {}, router: customRouterModule, } = {};
24
- if (moduleComponents) {
26
+ if (moduleComponents)
25
27
  ({
26
28
  interceptors = {},
27
29
  authConfigs = {},
28
30
  router: customRouterModule,
29
31
  } = moduleComponents);
30
- }
31
32
  const routerConfig = customRouterModule?.config || {};
32
33
  if (routerConfig?.disable === true)
33
34
  return router;
35
+ const customRouter = customRouterModule?.default;
36
+ if (customRouter && customRouterModule) {
37
+ if (router_validator_1.default.isExpressRouter(customRouter))
38
+ router.use(`/file-upload`, customRouter);
39
+ else
40
+ throw Error(`ValidationError: The exported router from file-upload.router.${(0, fs_helpers_1.getUserFileExtension)()} is not a valid express or arkos Router.`);
41
+ }
34
42
  let basePathname = fileUpload?.baseRoute || "/api/uploads/";
35
43
  if (!basePathname.startsWith("/"))
36
44
  basePathname = "/" + basePathname;
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../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":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport authService from \"../auth/auth.service\";\nimport fileUploadController from \"./file-upload.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\n\nconst router: Router = Router();\n\nexport async function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const { fileUpload } = arkosConfig;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents) {\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n }\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n router.get(\n `${basePathname}*`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n ),\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
1
+ {"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAmBA,kDAmIC;AAtJD,qCAAiC;AACjC,+DAAiE;AACjE,wEAA+C;AAC/C,sFAA4D;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BAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,0BAAe,CAAC,oBAAoB,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport authService from \"../auth/auth.service\";\nimport fileUploadController from \"./file-upload.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\n\nconst router: Router = Router();\n\nexport async function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const { fileUpload } = arkosConfig;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents)\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n const customRouter = customRouterModule?.default as Router;\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/file-upload`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from file-upload.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n router.get(\n `${basePathname}*`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n ),\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":";;;;;AAsBA,gCA8KC;AAKD,8EAGC;AA5MD,iDAAoD;AACpD,wDAAgC;AAChC,sDAA2E;AAC3E,qDAAiD;AACjD,sDAA6D;AAC7D,4CAAoB;AACpB,gDAAwB;AACxB,mDAA2B;AAC3B,kGAAuE;AAQvE,IAAI,KAAK,GAAwB,IAAI,CAAC;AACtC,IAAI,QAA8B,CAAC;AAK5B,KAAK,UAAU,UAAU,CAAC,UAAsB,EAAE;IACvD,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAC;IACrC,QAAQ,GAAG,IAAA,yCAAwB,GAAE,CAAC;IACtC,KAAK,GAAG,IAAI,CAAC;IACb,IAAI,cAAc,GAA0B,IAAI,CAAC;IAEjD,IAAI,CAAC;QACH,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAC/B,IAAI,YAAY,GAAG,KAAK,CAAC;QACzB,IAAI,eAAe,GAAG,IAAI,GAAG,EAAU,CAAC;QAExC,MAAM,OAAO,GAAG,IAAA,iCAAoB,GAAE,CAAC;QAEvC,MAAM,UAAU,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,OAAO,EAAE,CAAC,CAAC;QAErE,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAC/B,OAAO,CAAC,KAAK,CAAC,6CAA6C,UAAU,EAAE,CAAC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AAc;gBAAE,YAAY,CAAC,cAAc,CAAC,CAAC;YAEjD,IAAI,UAAU;gBAAE,UAAU,CAAC,KAAK,EAAE,CAAC;YAEnC,IAAI,KAAK,EAAE,CAAC;gBACV,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBAGtB,UAAU,CAAC,GAAG,EAAE;oBACd,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,MAAM;wBAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACpD,CAAC,EAAE,IAAI,CAAC,CAAC;YACX,CAAC;YAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC;QAGF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAG/B,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAE5D,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport chokidar from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\n// import smartFsWatcher from \"./utils/smart-fs-watcher\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n let restartingFiles = new Set<string>();\n\n const fileExt = getUserFileExtension();\n\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n child = spawn(\"npx\", [\"tsx-strict\", \"--watch\", entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n } else {\n child = spawn(\n \"npx\",\n [\"tsx-strict\", \"--no-type-check\", \"--watch\", entryPoint],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n // Function to handle server restart with debouncing\n const scheduleRestart = (reason: string, filePath?: string) => {\n if (filePath) restartingFiles.add(filePath);\n\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n\n restartTimeout = setTimeout(() => {\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n startServer();\n isRestarting = false;\n restartTimeout = null;\n if (filePath) restartingFiles.delete(filePath);\n }, 1000);\n };\n\n // Setup environment file watching\n const setupEnvWatcher = () => {\n const envWatcher = chokidar.watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (_, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n scheduleRestart(\"Environment files changed\", \"env-files\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n // Start the server\n startServer();\n\n // Setup watchers\n const envWatcher = setupEnvWatcher();\n\n const env = getEnv();\n const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(\n env,\n { logWarning: true }\n );\n\n console.info(`\\n \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${hostAndPort?.host}:${hostAndPort?.port}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}\\n`\n );\n\n // Enhanced cleanup function\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n // Handle process exit\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Handle uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
1
+ {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":";;;;;AAsBA,gCAwKC;AAKD,8EAGC;AAtMD,iDAAoD;AACpD,wDAAgC;AAChC,sDAA2E;AAC3E,qDAAiD;AACjD,sDAA6D;AAC7D,4CAAoB;AACpB,gDAAwB;AACxB,mDAA2B;AAC3B,kGAAuE;AAQvE,IAAI,KAAK,GAAwB,IAAI,CAAC;AACtC,IAAI,QAA8B,CAAC;AAK5B,KAAK,UAAU,UAAU,CAAC,UAAsB,EAAE;IACvD,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAC;IACrC,QAAQ,GAAG,IAAA,yCAAwB,GAAE,CAAC;IACtC,KAAK,GAAG,IAAI,CAAC;IACb,IAAI,cAAc,GAA0B,IAAI,CAAC;IAEjD,IAAI,CAAC;QACH,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAC/B,IAAI,YAAY,GAAG,KAAK,CAAC;QACzB,IAAI,eAAe,GAAG,IAAI,GAAG,EAAU,CAAC;QAExC,MAAM,OAAO,GAAG,IAAA,iCAAoB,GAAE,CAAC;QAEvC,MAAM,UAAU,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,OAAO,EAAE,CAAC,CAAC;QAErE,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAC/B,OAAO,CAAC,KAAK,CAAC,6CAA6C,UAAU,EAAE,CAAC,C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c;gBAAE,YAAY,CAAC,cAAc,CAAC,CAAC;YAEjD,IAAI,UAAU;gBAAE,UAAU,CAAC,KAAK,EAAE,CAAC;YAEnC,IAAI,KAAK,EAAE,CAAC;gBACV,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBAEtB,UAAU,CAAC,GAAG,EAAE;oBACd,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,MAAM;wBAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACpD,CAAC,EAAE,IAAI,CAAC,CAAC;YACX,CAAC;YAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC;QAGF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAG/B,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAE5D,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport chokidar from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\n// import smartFsWatcher from \"./utils/smart-fs-watcher\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n let restartingFiles = new Set<string>();\n\n const fileExt = getUserFileExtension();\n\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n child = spawn(\"npx\", [\"tsx-strict\", \"--watch\", entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n } else {\n child = spawn(\n \"npx\",\n [\"tsx-strict\", \"--no-type-check\", \"--watch\", entryPoint],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n const scheduleRestart = (reason: string, filePath?: string) => {\n if (filePath) restartingFiles.add(filePath);\n\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n\n restartTimeout = setTimeout(() => {\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n startServer();\n isRestarting = false;\n restartTimeout = null;\n if (filePath) restartingFiles.delete(filePath);\n }, 1000);\n };\n\n const setupEnvWatcher = () => {\n const envWatcher = chokidar.watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (_, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n scheduleRestart(\"Environment files changed\", \"env-files\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n startServer();\n\n const envWatcher = setupEnvWatcher();\n\n const env = getEnv();\n const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(\n env,\n { logWarning: true }\n );\n\n console.info(`\\n \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${hostAndPort?.host}:${hostAndPort?.port}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}\\n`\n );\n\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n // Handle process exit\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Handle uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
@@ -38,9 +38,8 @@ async function startCommand(options = {}) {
38
38
  shell: true,
39
39
  });
40
40
  process.on("SIGINT", () => {
41
- if (child) {
41
+ if (child)
42
42
  child.kill();
43
- }
44
43
  process.exit(0);
45
44
  });
46
45
  const checkConfig = async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":";;;;;AAoBA,oCAoGC;AAKD,4EAGC;AAhID,gDAAwB;AACxB,4CAAoB;AACpB,iDAAoD;AACpD,sDAA6D;AAC7D,8DAAyD;AACzD,sDAAqD;AACrD,kGAAuE;AACvE,kFAAyD;AAOzD,IAAI,KAAK,GAAwB,IAAI,CAAC;AACtC,IAAI,QAA8B,CAAC;AAK5B,KAAK,UAAU,YAAY,CAAC,UAAwB,EAAE;IAC3D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;IACpC,QAAQ,GAAG,IAAA,yCAAwB,GAAE,CAAC;IAEtC,IAAI,CAAC;QACH,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAG/B,MAAM,UAAU,GAAG,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;QAEvE,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,cAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAC1C,OAAO,CAAC,KAAK,CACX,qDAAqD,IAAA,yBAAY,EAAC,UAAU,CAAC,EAAE,CAChF,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC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CAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { importModule } from \"../helpers/global.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport async function startCommand(options: StartOptions = {}) {\n process.env.NODE_ENV = \"production\";\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n // Check for built app file\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n console.error(\n `❌ Could not find built application entry point at ${fullCleanCwd(entryPoint)}`\n );\n process.exit(1);\n }\n\n // Set environment variables\n const env: { [x: string]: string } = {\n ...process.env,\n NODE_ENV: \"production\",\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n };\n\n // Start the application\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n // Handle process exit\n process.on(\"SIGINT\", () => {\n if (child) {\n child.kill();\n }\n process.exit(0);\n });\n\n const checkConfig = async () => {\n try {\n const { getArkosConfig } = await importModule(\"../../server\");\n\n const config = getArkosConfig();\n\n if (config && config.available) {\n const hostAndPort =\n await portAndHostAllocator.getHostAndAvailablePort(env, {\n ...config,\n logWarning: true,\n });\n\n watermarkStamper.stamp({\n envFiles,\n port:\n \"port\" in config && config?.port !== undefined\n ? hostAndPort.port\n : undefined,\n host: hostAndPort.host,\n });\n return true;\n }\n return false;\n } catch (err: any) {\n if (!err?.message?.includes(\"../../server\")) console.error(err);\n return false;\n }\n };\n\n // Try to get config periodically\n const waitForConfig = async () => {\n let attempts = 0;\n const maxAttempts = 15;\n\n while (attempts < maxAttempts) {\n const ready = await checkConfig();\n if (ready) break;\n await new Promise((resolve) => setTimeout(resolve, 100));\n attempts++;\n }\n\n // Fall back to defaults if config never became available\n if (attempts >= maxAttempts) {\n if (env.CLI_PORT || env.PORT) portAndHostAllocator.logWarnings();\n\n watermarkStamper.stamp({\n envFiles,\n host: env.CLI_HOST || env.HOST,\n port: env.CLI_PORT || env.PORT,\n });\n }\n };\n\n waitForConfig();\n } catch (error) {\n console.error(\"❌ Production server failed to start:\", error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
1
+ {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":";;;;;AAoBA,oCA8FC;AAKD,4EAGC;AA1HD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAoD;AACpD,sDAA6D;AAC7D,8DAAyD;AACzD,sDAAqD;AACrD,kGAAuE;AACvE,kFAAyD;AAOzD,IAAI,KAAK,GAAwB,IAAI,CAAC;AACtC,IAAI,QAA8B,CAAC;AAK5B,KAAK,UAAU,YAAY,CAAC,UAAwB,EAAE;IAC3D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;IACpC,QAAQ,GAAG,IAAA,yCAAwB,GAAE,CAAC;IAEtC,IAAI,CAAC;QACH,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAE/B,MAAM,UAAU,GAAG,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;QAEvE,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,cAAI,CAA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,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,gCAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { importModule } from \"../helpers/global.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport async function startCommand(options: StartOptions = {}) {\n process.env.NODE_ENV = \"production\";\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n console.error(\n `❌ Could not find built application entry point at ${fullCleanCwd(entryPoint)}`\n );\n process.exit(1);\n }\n\n const env: { [x: string]: string } = {\n ...process.env,\n NODE_ENV: \"production\",\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n };\n\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n // Handle process exit\n process.on(\"SIGINT\", () => {\n if (child) child.kill();\n\n process.exit(0);\n });\n\n const checkConfig = async () => {\n try {\n const { getArkosConfig } = await importModule(\"../../server\");\n\n const config = getArkosConfig();\n\n if (config && config.available) {\n const hostAndPort =\n await portAndHostAllocator.getHostAndAvailablePort(env, {\n ...config,\n logWarning: true,\n });\n\n watermarkStamper.stamp({\n envFiles,\n port:\n \"port\" in config && config?.port !== undefined\n ? hostAndPort.port\n : undefined,\n host: hostAndPort.host,\n });\n return true;\n }\n return false;\n } catch (err: any) {\n if (!err?.message?.includes(\"../../server\")) console.error(err);\n return false;\n }\n };\n\n const waitForConfig = async () => {\n let attempts = 0;\n const maxAttempts = 15;\n\n while (attempts < maxAttempts) {\n const ready = await checkConfig();\n if (ready) break;\n await new Promise((resolve) => setTimeout(resolve, 100));\n attempts++;\n }\n\n if (attempts >= maxAttempts) {\n if (env.CLI_PORT || env.PORT) portAndHostAllocator.logWarnings();\n\n watermarkStamper.stamp({\n envFiles,\n host: env.CLI_HOST || env.HOST,\n port: env.CLI_PORT || env.PORT,\n });\n }\n };\n\n waitForConfig();\n } catch (error) {\n console.error(\"❌ Production server failed to start:\", error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
@@ -19,6 +19,6 @@ function killServerChildProcess() {
19
19
  (0, start_1.killProductionServerChildProcess)();
20
20
  }
21
21
  function getVersion() {
22
- return "1.3.5-beta";
22
+ return "1.3.5-canary.5";
23
23
  }
24
24
  //# sourceMappingURL=cli.helpers.js.map