arkos 1.0.16 → 1.0.18-beta

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.
@@ -22,8 +22,7 @@ const base_router_helpers_1 = require("./utils/helpers/base.router.helpers");
22
22
  function getPrismaModelsRouter(arkosConfigs) {
23
23
  return __awaiter(this, void 0, void 0, function* () {
24
24
  const router = (0, express_1.Router)();
25
- const models = (0, models_helpers_1.getModels)();
26
- yield Promise.all((0, base_router_helpers_1.setupRouters)(models, router));
25
+ yield Promise.all((0, base_router_helpers_1.setupRouters)((0, models_helpers_1.getModels)(), router));
27
26
  return router;
28
27
  });
29
28
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.js","sourceRoot":"","sources":["../../../../src/modules/base/base.router.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAQA,sDAoNC;AAED,oFAkBC;AAhPD,qCAAiC;AACjC,uDAA6E;AAC7E,uEAA+D;AAE/D,wEAA+C;AAE/C,6EAAmE;AAEnE,SAAsB,qBAAqB,CAAC,YAA0B;;QACpE,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;QAEhC,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;QA8M3B,MAAM,OAAO,CAAC,GAAG,CAAC,IAAA,kCAAY,EAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;QAEhD,OAAO,MAAM,CAAC;IAChB,CAAC;CAAA;AAED,SAAgB,oCAAoC;IAClD,MAAM,MAAM,GAAG,IAAA,gBAAM,GAAE,CAAC;IAExB,MAAM,CAAC,GAAG,CACR,mBAAmB,EACnB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,YAAY,EACzB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,yBAAyB,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EACtD,mCAAiB,CAClB,CAAC;IAEF,MAAM,CAAC,GAAG,CACR,sBAAsB,EACtB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,YAAY,EACzB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,yBAAyB,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EACtD,uCAAqB,CACtB,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getAvalibleRoutes, getAvailableResources } from \"./base.controller\";\nimport { getModels } from \"../../utils/helpers/models.helpers\";\n\nimport authService from \"../auth/auth.service\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport { setupRouters } from \"./utils/helpers/base.router.helpers\";\n\nexport async function getPrismaModelsRouter(arkosConfigs?: ArkosConfig) {\n const router: Router = Router();\n\n const models = getModels();\n\n // await new Promise((resolve) => {\n // models.forEach(async (model, i) => {\n // const modelNameInKebab = kebabCase(model);\n // const modelModules = await importPrismaModelModules(modelNameInKebab);\n // const { middlewares, authConfigs, prismaQueryOptions } = modelModules;\n\n // const routeName = pluralize.plural(modelNameInKebab);\n // const {\n // createOne,\n // findMany,\n // findOne,\n // updateOne,\n // deleteOne,\n // createMany,\n // updateMany,\n // deleteMany,\n // } = new BaseController(model);\n\n // router\n // .route(`/${routeName}`)\n // .post(\n // authService.handleAuthenticationControl(authConfigs, \"create\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"create\",\n // modelNameInKebab\n // ),\n // handleRequestBodyValidationAndTransformation(\n // modelNameInKebab,\n // \"create\"\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"createOne\"\n // ),\n // middlewares?.beforeCreateOne ?? createOne,\n // middlewares?.beforeCreateOne\n // ? createOne\n // : middlewares?.afterCreateOne ?? sendResponse,\n // middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n // ? middlewares?.afterCreateOne\n // : sendResponse,\n // sendResponse\n // )\n // .get(\n // authService.handleAuthenticationControl(authConfigs, \"view\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"view\",\n // modelNameInKebab\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"findMany\"\n // ),\n // middlewares?.beforeFindMany ?? findMany,\n // middlewares?.beforeFindMany\n // ? findMany\n // : middlewares?.afterFindMany ?? sendResponse,\n // middlewares?.beforeFindMany && middlewares?.afterFindMany\n // ? middlewares?.afterFindMany\n // : sendResponse,\n // sendResponse\n // );\n\n // router\n // .route(`/${routeName}/many`)\n // .post(\n // authService.handleAuthenticationControl(authConfigs, \"create\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"create\",\n // modelNameInKebab\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"createMany\"\n // ),\n // middlewares?.beforeCreateMany ?? createMany,\n // middlewares?.beforeCreateMany\n // ? createMany\n // : middlewares?.afterCreateMany ?? sendResponse,\n // middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n // ? middlewares?.afterCreateMany\n // : sendResponse,\n // sendResponse\n // )\n // .patch(\n // authService.handleAuthenticationControl(authConfigs, \"update\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"update\",\n // modelNameInKebab\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"updateMany\"\n // ),\n // middlewares?.beforeUpdateMany ?? updateMany,\n // middlewares?.beforeUpdateMany\n // ? updateMany\n // : middlewares?.afterUpdateMany ?? sendResponse,\n // middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n // ? middlewares?.afterUpdateMany\n // : sendResponse,\n // sendResponse\n // )\n // .delete(\n // authService.handleAuthenticationControl(authConfigs, \"delete\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"delete\",\n // modelNameInKebab\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"deleteMany\"\n // ),\n // middlewares?.beforeDeleteMany ?? deleteMany,\n // middlewares?.beforeDeleteMany\n // ? deleteMany\n // : middlewares?.afterDeleteMany ?? sendResponse,\n // middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n // ? middlewares?.afterDeleteMany\n // : sendResponse,\n // sendResponse\n // );\n\n // router\n // .route(`/${routeName}/:id`)\n // .get(\n // authService.handleAuthenticationControl(authConfigs, \"view\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"view\",\n // modelNameInKebab\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"findOne\"\n // ),\n // middlewares?.beforeFindOne ?? findOne,\n // middlewares?.beforeFindOne\n // ? findOne\n // : middlewares?.afterFindOne ?? sendResponse,\n // middlewares?.beforeFindOne && middlewares?.afterFindOne\n // ? middlewares?.afterFindOne\n // : sendResponse,\n // sendResponse\n // )\n // .patch(\n // authService.handleAuthenticationControl(authConfigs, \"update\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"update\",\n // modelNameInKebab\n // ),\n // handleRequestBodyValidationAndTransformation(\n // modelNameInKebab,\n // \"update\"\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"updateOne\"\n // ),\n // middlewares?.beforeUpdateOne ?? updateOne,\n // middlewares?.beforeUpdateOne\n // ? updateOne\n // : middlewares?.afterUpdateOne ?? sendResponse,\n // middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n // ? middlewares?.afterUpdateOne\n // : sendResponse,\n // sendResponse\n // )\n // .delete(\n // authService.handleAuthenticationControl(authConfigs, \"delete\"),\n // authService.handleActionAccessControl(\n // authConfigs,\n // \"delete\",\n // modelNameInKebab\n // ),\n // addPrismaQueryOptionsToRequestQuery<any>(\n // prismaQueryOptions as PrismaQueryOptions<any>,\n // \"deleteOne\"\n // ),\n // middlewares?.beforeDeleteOne ?? deleteOne,\n // middlewares?.beforeDeleteOne\n // ? deleteOne\n // : middlewares?.afterDeleteOne ?? sendResponse,\n // middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n // ? middlewares?.afterDeleteOne\n // : sendResponse,\n // sendResponse\n // );\n\n // if (i === models.length - 1) resolve(undefined);\n // });\n // });\n\n // return router;\n\n // Prepare an array of promises for Promise.all\n\n // Wait for all models to be processed in parallel\n await Promise.all(setupRouters(models, router));\n\n return router;\n}\n\nexport function getAvailableResourcesAndRoutesRouter(): Router {\n const router = Router();\n\n router.get(\n \"/available-routes\",\n authService?.authenticate,\n authService?.handleActionAccessControl({}, \"view\", \"\"),\n getAvalibleRoutes\n );\n\n router.get(\n \"/available-resources\",\n authService?.authenticate,\n authService?.handleActionAccessControl({}, \"view\", \"\"),\n getAvailableResources\n );\n\n return router;\n}\n"]}
1
+ {"version":3,"file":"base.router.js","sourceRoot":"","sources":["../../../../src/modules/base/base.router.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAQA,sDAMC;AAED,oFAkBC;AAlCD,qCAAiC;AACjC,uDAA6E;AAC7E,uEAA+D;AAE/D,wEAA+C;AAE/C,6EAAmE;AAEnE,SAAsB,qBAAqB,CAAC,YAA0B;;QACpE,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;QAEhC,MAAM,OAAO,CAAC,GAAG,CAAC,IAAA,kCAAY,EAAC,IAAA,0BAAS,GAAE,EAAE,MAAM,CAAC,CAAC,CAAC;QAErD,OAAO,MAAM,CAAC;IAChB,CAAC;CAAA;AAED,SAAgB,oCAAoC;IAClD,MAAM,MAAM,GAAG,IAAA,gBAAM,GAAE,CAAC;IAExB,MAAM,CAAC,GAAG,CACR,mBAAmB,EACnB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,YAAY,EACzB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,yBAAyB,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EACtD,mCAAiB,CAClB,CAAC;IAEF,MAAM,CAAC,GAAG,CACR,sBAAsB,EACtB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,YAAY,EACzB,sBAAW,aAAX,sBAAW,uBAAX,sBAAW,CAAE,yBAAyB,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EACtD,uCAAqB,CACtB,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getAvalibleRoutes, getAvailableResources } from \"./base.controller\";\nimport { getModels } from \"../../utils/helpers/models.helpers\";\n\nimport authService from \"../auth/auth.service\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport { setupRouters } from \"./utils/helpers/base.router.helpers\";\n\nexport async function getPrismaModelsRouter(arkosConfigs?: ArkosConfig) {\n const router: Router = Router();\n\n await Promise.all(setupRouters(getModels(), router));\n\n return router;\n}\n\nexport function getAvailableResourcesAndRoutesRouter(): Router {\n const router = Router();\n\n router.get(\n \"/available-routes\",\n authService?.authenticate,\n authService?.handleActionAccessControl({}, \"view\", \"\"),\n getAvalibleRoutes\n );\n\n router.get(\n \"/available-resources\",\n authService?.authenticate,\n authService?.handleActionAccessControl({}, \"view\", \"\"),\n getAvailableResources\n );\n\n return router;\n}\n"]}
@@ -90,36 +90,39 @@ function sendDevelopmentError(err, req, res) {
90
90
  var _a;
91
91
  console.error("[\x1b[31mERROR\x1b[0m]:", err);
92
92
  if (req.originalUrl.startsWith("/api"))
93
- return res.status(err.statusCode).json({
93
+ res.status(err.statusCode).json({
94
94
  message: err.message.split("\n")[err.message.split("\n").length - 1],
95
95
  error: err,
96
96
  stack: (_a = err.stack) === null || _a === void 0 ? void 0 : _a.split("\n"),
97
97
  });
98
- res.status(err.statusCode).json({
99
- title: "Something went wrong!",
100
- message: err.message,
101
- });
98
+ else
99
+ res.status(err.statusCode).json({
100
+ title: "Something went wrong!",
101
+ message: err.message,
102
+ });
102
103
  }
103
104
  function sendProductionError(err, req, res) {
104
105
  if (req.originalUrl.startsWith("/api")) {
105
- if (err.isOperational) {
106
- return res.status(err.statusCode).json({
106
+ if (err.isOperational)
107
+ res.status(err.statusCode).json({
107
108
  status: err.status,
108
109
  message: err.message,
109
110
  });
110
- }
111
- return res.status(500).json({
112
- status: "error",
113
- message: "Something went wrong!",
114
- });
111
+ else
112
+ res.status(500).json({
113
+ status: "error",
114
+ message: "Something went wrong!",
115
+ });
116
+ return;
115
117
  }
116
118
  if (err.isOperational) {
117
- return res.status(err.statusCode).json({
119
+ res.status(err.statusCode).json({
118
120
  title: "Something went wrong!",
119
121
  message: err.message,
120
122
  });
123
+ return;
121
124
  }
122
- return res.status(err.statusCode).json({
125
+ res.status(err.statusCode).json({
123
126
  title: "Something went wrong!",
124
127
  message: "Please try again later.",
125
128
  });
@@ -130,9 +133,9 @@ process.on("SIGTERM", () => {
130
133
  process.exit();
131
134
  }
132
135
  else {
133
- console.error("👋🏽 SIGTERM RECEIVED in Production. Shutting down gracefully!");
136
+ console.error("SIGTERM RECEIVED in Production. Shutting down gracefully!");
134
137
  server_1.server.close(() => {
135
- console.error("🔥 Process terminated");
138
+ console.error("Process terminated!!!");
136
139
  });
137
140
  }
138
141
  });
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAwEC;AA3FD,kEAAyC;AACzC,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAGlB,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,oBAAoB,CAAC,GAAG,EAAE,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AO,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,CACX,gEAAgE,CACjE,CAAC;QAEF,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACzC,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} next - 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 next: NextFunction\n): void {\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 sendDevelopmentError(err, req, res);\n return;\n }\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\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 === \"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 // Handle general error types (e.g., syntax errors, type errors, etc.)\n // if (err.name === \"SyntaxError\")\n // error = errorControllerHelper.handleSchemaSyntaxError(err);\n // if (err.name === \"TypeError\")\n // error = errorControllerHelper.handleClientTypeError(err);\n // if (err.name === \"BinaryError\")\n // error = errorControllerHelper.handleBinaryError(err);\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n // if (err.name === \"UnhandledPromiseRejection\")\n // error = errorControllerHelper.handleUnhandledPromiseError(err);\n if (!err.isOperational) error = new AppError(\"Something went wrong!\", 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(err: AppError, req: Request, res: Response) {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n\n if (req.originalUrl.startsWith(\"/api\"))\n return res.status(err.statusCode).json({\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n error: err,\n stack: err.stack?.split(\"\\n\"),\n });\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\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) {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational) {\n return res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n });\n }\n\n return res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n }\n\n if (err.isOperational) {\n return res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n }\n\n return res.status(err.statusCode).json({\n title: \"Something went wrong!\",\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(\n \"👋🏽 SIGTERM RECEIVED in Production. Shutting down gracefully!\"\n );\n\n server.close(() => {\n console.error(\"🔥 Process terminated\");\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error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ACjC,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;QACzC,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} next - 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 next: NextFunction\n): void {\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 sendDevelopmentError(err, req, res);\n return;\n }\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\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 === \"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 // Handle general error types (e.g., syntax errors, type errors, etc.)\n // if (err.name === \"SyntaxError\")\n // error = errorControllerHelper.handleSchemaSyntaxError(err);\n // if (err.name === \"TypeError\")\n // error = errorControllerHelper.handleClientTypeError(err);\n // if (err.name === \"BinaryError\")\n // error = errorControllerHelper.handleBinaryError(err);\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n // if (err.name === \"UnhandledPromiseRejection\")\n // error = errorControllerHelper.handleUnhandledPromiseError(err);\n if (!err.isOperational) error = new AppError(\"Something went wrong!\", 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 console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n error: err,\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\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 });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\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 });\n }\n});\n"]}
@@ -45,73 +45,115 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
45
45
  return (mod && mod.__esModule) ? mod : { "default": mod };
46
46
  };
47
47
  Object.defineProperty(exports, "__esModule", { value: true });
48
- exports.prismaModelRelationFields = exports.models = exports.prismaModelsUniqueFields = exports.prismaModelsModules = void 0;
48
+ exports.prismaModelsUniqueFields = exports.models = exports.prismaModelRelationFields = exports.prismaModelsModules = void 0;
49
49
  exports.getModelModules = getModelModules;
50
+ exports.getFileModelModulesFileStructure = getFileModelModulesFileStructure;
51
+ exports.processSubdir = processSubdir;
50
52
  exports.importPrismaModelModules = importPrismaModelModules;
51
53
  exports.getAllPrismaFiles = getAllPrismaFiles;
54
+ exports.initializePrismaModels = initializePrismaModels;
52
55
  exports.getPrismaModelRelations = getPrismaModelRelations;
53
56
  exports.getModels = getModels;
54
57
  exports.getModelUniqueFields = getModelUniqueFields;
55
58
  const path_1 = __importDefault(require("path"));
56
59
  const fs_1 = __importDefault(require("fs"));
57
60
  const change_case_helpers_1 = require("../../utils/helpers/change-case.helpers");
58
- const arkos_env_1 = __importDefault(require("../arkos-env"));
59
61
  const fs_helpers_1 = require("./fs.helpers");
62
+ const global_helpers_1 = require("./global.helpers");
60
63
  exports.prismaModelsModules = {};
61
64
  function getModelModules(modelName) {
62
65
  return exports.prismaModelsModules[(0, change_case_helpers_1.kebabCase)(modelName)];
63
66
  }
64
- function importPrismaModelModules(modelName) {
67
+ function getFileModelModulesFileStructure(modelName) {
68
+ const kebabModelName = (0, change_case_helpers_1.kebabCase)(modelName).toLowerCase();
69
+ const lowerModelName = kebabModelName.toLowerCase();
70
+ const isAuthModule = modelName.toLowerCase() === "auth";
71
+ return {
72
+ core: {
73
+ service: `${kebabModelName}.service.${fs_helpers_1.userFileExtension}`,
74
+ controller: `${kebabModelName}.controller.${fs_helpers_1.userFileExtension}`,
75
+ middlewares: `${kebabModelName}.middlewares.${fs_helpers_1.userFileExtension}`,
76
+ authConfigs: `${kebabModelName}.auth-configs.${fs_helpers_1.userFileExtension}`,
77
+ prismaQueryOptions: `${kebabModelName}.prisma-query-options.${fs_helpers_1.userFileExtension}`,
78
+ router: `${kebabModelName}.router.${fs_helpers_1.userFileExtension}`,
79
+ },
80
+ dtos: isAuthModule
81
+ ? {
82
+ login: `login.dto.${fs_helpers_1.userFileExtension}`,
83
+ signup: `signup.dto.${fs_helpers_1.userFileExtension}`,
84
+ updateMe: `update-me.dto.${fs_helpers_1.userFileExtension}`,
85
+ updatePassword: `update-password.dto.${fs_helpers_1.userFileExtension}`,
86
+ }
87
+ : {
88
+ model: `${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
89
+ create: `create-${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
90
+ update: `update-${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
91
+ query: `query-${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
92
+ },
93
+ schemas: isAuthModule
94
+ ? {
95
+ login: `login.schema.${fs_helpers_1.userFileExtension}`,
96
+ signup: `signup.schema.${fs_helpers_1.userFileExtension}`,
97
+ updateMe: `update-me.schema.${fs_helpers_1.userFileExtension}`,
98
+ updatePassword: `update-password.schema.${fs_helpers_1.userFileExtension}`,
99
+ }
100
+ : {
101
+ model: `${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
102
+ create: `create-${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
103
+ update: `update-${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
104
+ query: `query-${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
105
+ },
106
+ };
107
+ }
108
+ function processSubdir(modelName, type, result) {
65
109
  return __awaiter(this, void 0, void 0, function* () {
66
- const kebabModelName = (0, change_case_helpers_1.kebabCase)(modelName).toLowerCase();
67
- const lowerModelName = kebabModelName.toLowerCase();
110
+ const moduleDir = path_1.default.resolve(process.cwd(), "src", "modules", (0, change_case_helpers_1.kebabCase)(modelName));
111
+ const subdir = path_1.default.join(moduleDir, type);
68
112
  const pascalModelName = (0, change_case_helpers_1.pascalCase)(modelName);
69
- const moduleDir = path_1.default.resolve(process.cwd(), "src", "modules", modelName);
113
+ const fileStructure = getFileModelModulesFileStructure(modelName);
70
114
  const isAuthModule = modelName.toLowerCase() === "auth";
71
- const fileStructure = {
72
- core: {
73
- service: `${kebabModelName}.service.${fs_helpers_1.userFileExtension}`,
74
- controller: `${kebabModelName}.controller.${fs_helpers_1.userFileExtension}`,
75
- middlewares: `${kebabModelName}.middlewares.${fs_helpers_1.userFileExtension}`,
76
- authConfigs: `${kebabModelName}.auth-configs.${fs_helpers_1.userFileExtension}`,
77
- prismaQueryOptions: `${kebabModelName}.prisma-query-options.${fs_helpers_1.userFileExtension}`,
78
- router: `${kebabModelName}.router.${fs_helpers_1.userFileExtension}`,
79
- },
80
- dtos: isAuthModule
81
- ? {
82
- login: `login.dto.${fs_helpers_1.userFileExtension}`,
83
- signup: `signup.dto.${fs_helpers_1.userFileExtension}`,
84
- updateMe: `update-me.dto.${fs_helpers_1.userFileExtension}`,
85
- updatePassword: `update-password.dto.${fs_helpers_1.userFileExtension}`,
115
+ try {
116
+ yield fs_1.default.promises.access(subdir).catch(() => {
117
+ return;
118
+ });
119
+ yield Promise.all(Object.entries(fileStructure[type]).map((_a) => __awaiter(this, [_a], void 0, function* ([key, fileName]) {
120
+ const filePath = path_1.default.join(subdir, fileName);
121
+ try {
122
+ const module = yield Promise.resolve(`${filePath}`).then(s => __importStar(require(s))).catch(() => null);
123
+ if (module) {
124
+ if (isAuthModule) {
125
+ const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);
126
+ const expectedName = `${pascalKey}${type === "dtos" ? "Dto" : "Schema"}`;
127
+ result[type][key] = module.default;
128
+ }
129
+ else {
130
+ const expectedName = key === "model"
131
+ ? `${pascalModelName}${type === "dtos" ? "Dto" : "Schema"}`
132
+ : `${key.charAt(0).toUpperCase() + key.slice(1)}${pascalModelName}${type === "dtos" ? "Dto" : "Schema"}`;
133
+ result[type][key] = module.default;
134
+ }
135
+ }
86
136
  }
87
- : {
88
- model: `${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
89
- create: `create-${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
90
- update: `update-${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
91
- query: `query-${lowerModelName}.dto.${fs_helpers_1.userFileExtension}`,
92
- },
93
- schemas: isAuthModule
94
- ? {
95
- login: `login.schema.${fs_helpers_1.userFileExtension}`,
96
- signup: `signup.schema.${fs_helpers_1.userFileExtension}`,
97
- updateMe: `update-me.schema.${fs_helpers_1.userFileExtension}`,
98
- updatePassword: `update-password.schema.${fs_helpers_1.userFileExtension}`,
137
+ catch (error) {
99
138
  }
100
- : {
101
- model: `${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
102
- create: `create-${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
103
- update: `update-${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
104
- query: `query-${lowerModelName}.schema.${fs_helpers_1.userFileExtension}`,
105
- },
106
- };
139
+ })));
140
+ }
141
+ catch (error) {
142
+ }
143
+ });
144
+ }
145
+ function importPrismaModelModules(modelName) {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ const moduleDir = path_1.default.resolve(process.cwd(), "src", "modules", modelName);
107
148
  const result = {
108
149
  dtos: {},
109
150
  schemas: {},
110
151
  };
152
+ const fileStructure = getFileModelModulesFileStructure(modelName);
111
153
  yield Promise.all(Object.entries(fileStructure.core).map((_a) => __awaiter(this, [_a], void 0, function* ([key, fileName]) {
112
154
  const filePath = path_1.default.join(moduleDir, fileName);
113
155
  try {
114
- const module = yield Promise.resolve(`${filePath}`).then(s => __importStar(require(s))).catch(() => null);
156
+ const module = yield (0, global_helpers_1.importModule)(filePath).catch(() => null);
115
157
  if (module) {
116
158
  if (key === "middlewares")
117
159
  result[key] = module;
@@ -119,49 +161,17 @@ function importPrismaModelModules(modelName) {
119
161
  result[key] = module.default || module;
120
162
  }
121
163
  }
122
- catch (error) {
123
- }
164
+ catch (_b) { }
124
165
  })));
125
- const processSubdir = (type) => __awaiter(this, void 0, void 0, function* () {
126
- const subdir = path_1.default.join(moduleDir, type);
127
- try {
128
- yield fs_1.default.promises.access(subdir).catch(() => {
129
- return;
130
- });
131
- yield Promise.all(Object.entries(fileStructure[type]).map((_a) => __awaiter(this, [_a], void 0, function* ([key, fileName]) {
132
- const filePath = path_1.default.join(subdir, fileName);
133
- try {
134
- const module = yield Promise.resolve(`${filePath}`).then(s => __importStar(require(s))).catch(() => null);
135
- if (module) {
136
- if (isAuthModule) {
137
- const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);
138
- const expectedName = `${pascalKey}${type === "dtos" ? "Dto" : "Schema"}`;
139
- result[type][key] = module.default;
140
- }
141
- else {
142
- const expectedName = key === "model"
143
- ? `${pascalModelName}${type === "dtos" ? "Dto" : "Schema"}`
144
- : `${key.charAt(0).toUpperCase() + key.slice(1)}${pascalModelName}${type === "dtos" ? "Dto" : "Schema"}`;
145
- result[type][key] = module.default;
146
- }
147
- }
148
- }
149
- catch (error) {
150
- }
151
- })));
152
- }
153
- catch (error) {
154
- }
155
- });
156
- yield Promise.all([processSubdir("dtos"), processSubdir("schemas")]);
166
+ yield Promise.all([
167
+ processSubdir(modelName, "dtos", result),
168
+ processSubdir(modelName, "schemas", result),
169
+ ]);
157
170
  exports.prismaModelsModules[modelName] = result;
158
171
  return result;
159
172
  });
160
173
  }
161
- const schemaFolderPath = process.env.PRISMA_SCHEMA_PATH || arkos_env_1.default.PRISMA_SCHEMA_PATH;
162
- const prismaModelRelationFields = {};
163
- exports.prismaModelRelationFields = prismaModelRelationFields;
164
- const prismaContent = [];
174
+ exports.prismaModelRelationFields = {};
165
175
  function getAllPrismaFiles(dirPath, fileList = []) {
166
176
  const files = fs_1.default.readdirSync(dirPath);
167
177
  files === null || files === void 0 ? void 0 : files.forEach((file) => {
@@ -176,102 +186,98 @@ function getAllPrismaFiles(dirPath, fileList = []) {
176
186
  });
177
187
  return fileList;
178
188
  }
179
- const files = getAllPrismaFiles("./prisma");
180
- for (const file of files) {
181
- const content = fs_1.default.readFileSync(file, "utf-8");
182
- prismaContent.push(content);
183
- }
184
189
  const modelRegex = /model\s+(\w+)\s*{/g;
185
- const models = [];
186
- exports.models = models;
190
+ exports.models = [];
187
191
  exports.prismaModelsUniqueFields = [];
188
- prismaContent.join("\n").replace(modelRegex, (_, modelName) => {
189
- if (!models.includes(modelName))
190
- models.push((0, change_case_helpers_1.camelCase)(modelName.trim()));
191
- return modelName;
192
- });
193
- for (const model of models) {
194
- const modelName = (0, change_case_helpers_1.pascalCase)(model);
195
- let modelFile;
192
+ function initializePrismaModels(testName) {
193
+ const prismaContent = [];
194
+ const files = getAllPrismaFiles("./prisma");
196
195
  for (const file of files) {
197
- const filePath = path_1.default.join(file);
198
- const stats = fs_1.default.statSync(filePath);
199
- if (stats.isFile()) {
200
- const content = fs_1.default.readFileSync(filePath, "utf-8");
196
+ const content = fs_1.default.readFileSync(file, "utf-8");
197
+ if (!prismaContent.includes(content))
201
198
  prismaContent.push(content);
202
- if (content.includes(`model ${modelName} {`)) {
203
- modelFile = file;
204
- break;
205
- }
206
- }
207
- }
208
- if (!modelFile) {
209
- throw new Error(`Model ${modelName} not found`);
210
199
  }
211
- const content = fs_1.default.readFileSync(path_1.default.join(modelFile), "utf-8");
212
- const modelStart = content.indexOf(`model ${modelName} {`);
213
- const modelEnd = content.indexOf("}", modelStart);
214
- const modelDefinition = content.slice(modelStart, modelEnd);
215
- const relations = {
216
- singular: [],
217
- list: [],
218
- };
219
- const lines = modelDefinition.split("\n");
220
- for (const line of lines) {
221
- const trimmedLine = line.trim();
222
- if (!trimmedLine ||
223
- trimmedLine.startsWith("model") ||
224
- trimmedLine.startsWith("//"))
225
- continue;
226
- const [fieldName, type] = trimmedLine.split(/\s+/);
227
- const isUnique = trimmedLine.includes("@unique");
228
- if (isUnique)
229
- exports.prismaModelsUniqueFields[model] = [
230
- ...(exports.prismaModelsUniqueFields[model] || []),
231
- { name: fieldName, type, isUnique },
232
- ];
233
- const cleanType = type === null || type === void 0 ? void 0 : type.replace("[]", "").replace("?", "");
234
- if (trimmedLine.includes("@relation") ||
235
- trimmedLine.match(/\s+\w+(\[\])?(\s+@|$)/) ||
236
- models.includes((0, change_case_helpers_1.camelCase)(cleanType || ""))) {
237
- const modelStart = content.indexOf(`enum ${cleanType} {`);
238
- if (!cleanType ||
239
- modelStart >= 0 ||
240
- cleanType === "String" ||
241
- cleanType === "Int" ||
242
- cleanType === "Float" ||
243
- cleanType === "Boolean" ||
244
- cleanType === "DateTime" ||
245
- cleanType === "Bytes" ||
246
- cleanType === "Decimal" ||
247
- cleanType === "BigInt" ||
248
- cleanType === "Json") {
200
+ const content = prismaContent
201
+ .join("\n")
202
+ .replace(modelRegex, (_, modelName) => {
203
+ if (!exports.models.includes(modelName))
204
+ exports.models.push((0, change_case_helpers_1.camelCase)(modelName.trim()));
205
+ return `model ${modelName} {`;
206
+ });
207
+ for (const model of exports.models) {
208
+ const modelName = (0, change_case_helpers_1.pascalCase)(model);
209
+ const modelStart = content.indexOf(`model ${modelName} {`);
210
+ const modelEnd = content.indexOf("}", modelStart);
211
+ const modelDefinition = content.slice(modelStart, modelEnd);
212
+ const relations = {
213
+ singular: [],
214
+ list: [],
215
+ };
216
+ const lines = modelDefinition.split("\n");
217
+ for (const line of lines) {
218
+ const trimmedLine = line.trim();
219
+ if (!trimmedLine ||
220
+ trimmedLine.startsWith("model") ||
221
+ trimmedLine.startsWith("//"))
249
222
  continue;
223
+ const [fieldName, type] = trimmedLine.split(/\s+/);
224
+ const isUnique = trimmedLine.includes("@unique");
225
+ if (isUnique) {
226
+ const existingFields = exports.prismaModelsUniqueFields[model] || [];
227
+ const alreadyExists = existingFields.some((field) => field.name === fieldName &&
228
+ field.type === type &&
229
+ field.isUnique === isUnique);
230
+ if (!alreadyExists) {
231
+ exports.prismaModelsUniqueFields[model] = [
232
+ ...existingFields,
233
+ { name: fieldName, type, isUnique },
234
+ ];
235
+ }
250
236
  }
251
- if (!(type === null || type === void 0 ? void 0 : type.includes("[]"))) {
252
- relations.singular.push({
253
- name: fieldName,
254
- type: cleanType,
255
- });
256
- }
257
- else {
258
- relations.list.push({
259
- name: fieldName,
260
- type: cleanType,
261
- });
237
+ const cleanType = type === null || type === void 0 ? void 0 : type.replace("[]", "").replace("?", "");
238
+ if (trimmedLine.includes("@relation") ||
239
+ trimmedLine.match(/\s+\w+(\[\])?(\s+@|$)/) ||
240
+ exports.models.includes((0, change_case_helpers_1.camelCase)(cleanType || ""))) {
241
+ const modelStart = content.indexOf(`enum ${cleanType} {`);
242
+ if (!cleanType ||
243
+ modelStart >= 0 ||
244
+ cleanType === "String" ||
245
+ cleanType === "Int" ||
246
+ cleanType === "Float" ||
247
+ cleanType === "Boolean" ||
248
+ cleanType === "DateTime" ||
249
+ cleanType === "Bytes" ||
250
+ cleanType === "Decimal" ||
251
+ cleanType === "BigInt" ||
252
+ cleanType === "Json") {
253
+ continue;
254
+ }
255
+ if (!(type === null || type === void 0 ? void 0 : type.includes("[]"))) {
256
+ relations.singular.push({
257
+ name: fieldName,
258
+ type: cleanType,
259
+ });
260
+ }
261
+ else {
262
+ relations.list.push({
263
+ name: fieldName,
264
+ type: cleanType,
265
+ });
266
+ }
262
267
  }
268
+ exports.prismaModelRelationFields[modelName] = relations;
263
269
  }
264
- prismaModelRelationFields[modelName] = relations;
265
270
  }
266
271
  }
272
+ initializePrismaModels();
267
273
  function getPrismaModelRelations(modelName) {
268
274
  modelName = (0, change_case_helpers_1.pascalCase)(modelName);
269
- if (!(modelName in prismaModelRelationFields))
275
+ if (!(modelName in exports.prismaModelRelationFields))
270
276
  return;
271
- return prismaModelRelationFields[modelName];
277
+ return exports.prismaModelRelationFields[modelName];
272
278
  }
273
279
  function getModels() {
274
- return models;
280
+ return exports.models;
275
281
  }
276
282
  function getModelUniqueFields(modelName) {
277
283
  return exports.prismaModelsUniqueFields[modelName];