arkos 1.0.1-beta → 1.0.2-alpha

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 (65) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/app.js +1 -1
  3. package/dist/cjs/app.js.map +1 -1
  4. package/dist/cjs/exports/services/index.js +3 -3
  5. package/dist/cjs/exports/services/index.js.map +1 -1
  6. package/dist/cjs/modules/auth/__tests__/auth.controller.test.js +0 -1
  7. package/dist/cjs/modules/auth/__tests__/auth.controller.test.js.map +1 -1
  8. package/dist/cjs/modules/auth/__tests__/auth.service.test.js +470 -0
  9. package/dist/cjs/modules/auth/__tests__/auth.service.test.js.map +1 -0
  10. package/dist/cjs/modules/auth/auth.service.js +30 -9
  11. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  12. package/dist/cjs/modules/email/email.service.js +12 -7
  13. package/dist/cjs/modules/email/email.service.js.map +1 -1
  14. package/dist/cjs/modules/file-uploader/__tests__/file-uploader.service.test.js +402 -0
  15. package/dist/cjs/modules/file-uploader/__tests__/file-uploader.service.test.js.map +1 -0
  16. package/dist/cjs/modules/file-uploader/file-uploader.controller.js +226 -0
  17. package/dist/cjs/modules/file-uploader/file-uploader.controller.js.map +1 -0
  18. package/dist/cjs/modules/file-uploader/file-uploader.router.js +50 -0
  19. package/dist/cjs/modules/file-uploader/file-uploader.router.js.map +1 -0
  20. package/dist/cjs/modules/file-uploader/file-uploader.service.js +299 -0
  21. package/dist/cjs/modules/file-uploader/file-uploader.service.js.map +1 -0
  22. package/dist/cjs/modules/file-uploader/utils/helpers/__tests__/file-uploader.helpers.test.js +164 -0
  23. package/dist/cjs/modules/file-uploader/utils/helpers/__tests__/file-uploader.helpers.test.js.map +1 -0
  24. package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js +85 -0
  25. package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +1 -0
  26. package/dist/cjs/server.js +1 -1
  27. package/dist/cjs/server.js.map +1 -1
  28. package/dist/cjs/types/arkos-config.js.map +1 -1
  29. package/dist/cjs/types/auth.js.map +1 -1
  30. package/dist/cjs/types/index.js.map +1 -1
  31. package/dist/cjs/utils/helpers/models.helpers.js +19 -6
  32. package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
  33. package/dist/es2020/app.js +1 -1
  34. package/dist/es2020/app.js.map +1 -1
  35. package/dist/es2020/exports/services/index.js +1 -1
  36. package/dist/es2020/exports/services/index.js.map +1 -1
  37. package/dist/es2020/modules/auth/auth.service.js +30 -9
  38. package/dist/es2020/modules/auth/auth.service.js.map +1 -1
  39. package/dist/es2020/modules/email/email.service.js +12 -7
  40. package/dist/es2020/modules/email/email.service.js.map +1 -1
  41. package/dist/es2020/modules/file-uploader/file-uploader.controller.js +220 -0
  42. package/dist/es2020/modules/file-uploader/file-uploader.controller.js.map +1 -0
  43. package/dist/es2020/modules/file-uploader/file-uploader.router.js +44 -0
  44. package/dist/es2020/modules/file-uploader/file-uploader.router.js.map +1 -0
  45. package/dist/es2020/modules/file-uploader/file-uploader.service.js +291 -0
  46. package/dist/es2020/modules/file-uploader/file-uploader.service.js.map +1 -0
  47. package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js +77 -0
  48. package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +1 -0
  49. package/dist/es2020/server.js +1 -1
  50. package/dist/es2020/server.js.map +1 -1
  51. package/dist/es2020/types/arkos-config.js.map +1 -1
  52. package/dist/es2020/types/auth.js.map +1 -1
  53. package/dist/es2020/types/index.js.map +1 -1
  54. package/dist/es2020/utils/helpers/models.helpers.js +19 -6
  55. package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
  56. package/dist/types/exports/services/index.d.ts +1 -1
  57. package/dist/types/modules/email/email.service.d.ts +1 -2
  58. package/dist/types/modules/file-uploader/file-uploader.controller.d.ts +3 -0
  59. package/dist/types/modules/file-uploader/file-uploader.router.d.ts +3 -0
  60. package/dist/types/modules/file-uploader/file-uploader.service.d.ts +30 -0
  61. package/dist/types/modules/file-uploader/utils/helpers/file-uploader.helpers.d.ts +2 -0
  62. package/dist/types/types/arkos-config.d.ts +8 -1
  63. package/dist/types/types/auth.d.ts +2 -2
  64. package/dist/types/types/index.d.ts +1 -0
  65. package/package.json +6 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-uploader.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/file-uploader/utils/helpers/file-uploader.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,+BAAiC;AACjC,+CAAoD;AACpD,wDAAgC;AAKhC,MAAM,oBAAoB,GAAG,CAAC,QAAgB,EAAE,QAAgB,EAAE,EAAE;IAClE,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;IAExC,MAAM,aAAa,GAAG,CAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,aAAa,KAAI,UAAU,CAAC;IAC9D,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAEnC,OAAO,cAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;IACtD,CAAC;SAAM,CAAC;QAEN,OAAO,CACL,GAAG,QAAQ,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,aAAa,GAAG,EAAE,EAAE,CAAC,CAC3E,CAAC;IACJ,CAAC;AACH,CAAC,CAAC;AAKK,MAAM,WAAW,GAAG,CACzB,QAAgB,EAChB,OAAe,EACf,SAAiB,EACjB,QAAgB,EACC,EAAE;IACnB,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC9D,OAAO,GAAG,OAAO,GAAG,SAAS,IAAI,YAAY,EAAE,CAAC;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C,QAAQ,CAAC,CAAC;YACnC,MAAM,IAAA,gBAAS,EAAC,YAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;QAEf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAA,CAAC;AAtEW,QAAA,YAAY,gBAsEvB","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport sharp from \"sharp\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../../../server\";\nimport mimetype from \"mimetype\";\n\n/**\n * Generates the correct relative path regardless of upload directory location\n */\nconst generateRelativePath = (filePath: string, fileType: string) => {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n if (baseUploadDir.startsWith(\"..\")) {\n // For paths outside project directory\n return path.join(fileType, path.basename(filePath));\n } else {\n // For paths within project\n return (\n `${fileType}/` + filePath.replace(`${process.cwd()}${baseUploadDir}/`, \"\")\n );\n }\n};\n\n/**\n * Handles basic file processing for non-image files\n */\nexport const processFile = async (\n filePath: string,\n baseURL: string,\n baseRoute: string,\n fileType: string\n): Promise<string> => {\n const relativePath = generateRelativePath(filePath, fileType);\n return `${baseURL}${baseRoute}/${relativePath}`;\n};\n\n/**\n * Processes image files using Sharp for resizing and format conversion\n */\nexport const processImage = async (\n filePath: string,\n baseURL: string,\n baseRoute: string,\n options: Record<string, any>,\n fileType: string\n): Promise<string | null> => {\n const ext = path.extname(filePath).toLowerCase();\n const originalFormat = ext.replace(\".\", \"\");\n const outputFormat = options.format || originalFormat;\n\n if (!mimetype.lookup(ext)?.includes(\"image\")) {\n const relativePath = generateRelativePath(filePath, fileType);\n return `${baseURL}${baseRoute}/${relativePath}`;\n }\n\n // Create a temp filename with original name + random string\n const tempName = `${path.basename(filePath, ext)}_${Date.now()}${ext}`;\n const tempPath = path.join(path.dirname(filePath), tempName);\n\n try {\n let transformer = sharp(filePath);\n const metadata = await transformer.metadata();\n\n // Apply resize transformations if requested\n if (options.resizeTo && metadata.width && metadata.height) {\n const targetSize = options.resizeTo;\n const scaleFactor =\n targetSize / Math.min(metadata.width, metadata.height);\n const newWidth = Math.round(metadata.width * scaleFactor);\n const newHeight = Math.round(metadata.height * scaleFactor);\n transformer = transformer.resize(newWidth, newHeight);\n } else if (options.width || options.height) {\n transformer = transformer.resize(\n options.width || null,\n options.height || null,\n {\n fit: \"inside\",\n }\n );\n }\n\n // Apply format transformations if requested\n if (outputFormat === \"webp\") {\n transformer = transformer.toFormat(\"webp\");\n } else if (outputFormat === \"jpeg\" || outputFormat === \"jpg\") {\n transformer = transformer.toFormat(\"jpeg\");\n }\n\n // Save to temp file first\n await transformer.toFile(tempPath);\n\n // Rename temp file to original filename\n await promisify(fs.rename)(tempPath, filePath);\n\n // Return the public URL for the file\n const relativePath = generateRelativePath(filePath, fileType);\n\n // console.log(`${baseURL}${baseRoute}/${relativePath}`);\n return `${baseURL}${baseRoute}/${relativePath}`;\n } catch (error) {\n // Clean up temp file if it exists\n try {\n await promisify(fs.stat)(tempPath);\n await promisify(fs.unlink)(tempPath);\n } catch (err) {\n // If temp file doesn't exist, no need to clean up\n }\n throw error;\n }\n};\n"]}
@@ -1 +1 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,t,n,s){function u(r){return r instanceof n?r:new n(function(i){i(r)})}return new(n||(n=Promise))(function(r,i){function l(o){try{p(s.next(o))}catch(c){i(c)}}function a(o){try{p(s.throw(o))}catch(c){i(c)}}function p(o){o.done?r(o.value):u(o.value).then(l,a)}p((s=s.apply(e,t||[])).next())})},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper"));process.on("uncaughtException",e=>{console.error("UNCAUGHT EXCEPTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.PORT)||8e3};function initApp(){return __awaiter(this,arguments,void 0,function*(e={}){_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const t=Number(process.env.PORT)||_arkosConfig.port||8e3;return _app=yield(0,app_1.bootstrap)(_arkosConfig),t&&(exports.server=server=_app.listen(e?.host?[t,e?.host]:t,()=>{const n=new Date().toTimeString().split(" ")[0];console.info(`[\x1B[32mREADY\x1B[0m] \x1B[90m${n}\x1B[0m App running on port \x1B[33m${t}\x1B[0m, server waiting on http://localhost:${t}`),process.env.NODE_ENV&&console.log(`${`Environment: ${process.env.NODE_ENV}`}`)})),_app})}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),server.close(()=>{process.exit(1)})});function getArkosConfig(){return _arkosConfig}function getExpressApp(){return _app}
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,n,s){function u(r){return r instanceof n?r:new n(function(i){i(r)})}return new(n||(n=Promise))(function(r,i){function l(o){try{p(s.next(o))}catch(c){i(c)}}function a(o){try{p(s.throw(o))}catch(c){i(c)}}function p(o){o.done?r(o.value):u(o.value).then(l,a)}p((s=s.apply(e,t||[])).next())})},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper"));process.on("uncaughtException",e=>{console.error("UNCAUGHT EXCEPTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:8e3};function initApp(){return __awaiter(this,arguments,void 0,function*(e={}){_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const t=_arkosConfig.port;return _app=yield(0,app_1.bootstrap)(_arkosConfig),t&&(exports.server=server=_app.listen(e?.host?[t,e?.host]:t,()=>{const n=new Date().toTimeString().split(" ")[0];console.info(`[\x1B[32mREADY\x1B[0m] \x1B[90m${n}\x1B[0m App running on port \x1B[33m${t}\x1B[0m, server waiting on http://localhost:${t}`),process.env.NODE_ENV&&console.log(`${`Environment: ${process.env.NODE_ENV}`}`)})),_app})}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),server.close(()=>{process.exit(1)})});function getArkosConfig(){return _arkosConfig}function getExpressApp(){return _app}
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAmEA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAxExB,+BAAkC;AAElC,wFAAyD;AAEzD,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;AAClB,IAAI,YAAY,GAAgB;IAC9B,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;CACvC,CAAC;AAgBF,SAAe,OAAO;yDAAC,cAA2B,EAAE;QAClD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CAAC,CAAC,CAAC;AAEH,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\nlet _arkosConfig: ArkosConfig = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.PORT) || 8000,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `PORT` environment variable.\n * 2. The `port` argument passed to the function.\n * 3. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = Number(process.env.PORT) || _arkosConfig.port || 8000;\n _app = await bootstrap(_arkosConfig);\n\n if (port)\n server = _app.listen(\n arkosConfig?.host ? [port, arkosConfig?.host!] : port,\n () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n );\n\n if (!!process.env.NODE_ENV)\n console.log(`${`Environment: ${process.env.NODE_ENV}`}`);\n }\n );\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n server.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAkEA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAvExB,+BAAkC;AAElC,wFAAyD;AAEzD,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;AAClB,IAAI,YAAY,GAAgB;IAC9B,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,IAAI;CACX,CAAC;AAeF,SAAe,OAAO;yDAAC,cAA2B,EAAE;QAClD,YAAY,GAAG,IAAA,0BAAS,EAAC,YAAY,EAAE,WAAW,CAAC,CAAC;QAEpD,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC;QAC/B,IAAI,GAAG,MAAM,IAAA,eAAS,EAAC,YAAY,CAAC,CAAC;QAErC,IAAI,IAAI;YACN,iBAAA,MAAM,GAAG,IAAI,CAAC,MAAM,CAClB,CAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,IAAI,EAAC,CAAC,CAAC,CAAC,IAAI,EAAE,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,IAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EACrD,GAAG,EAAE;gBACH,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;gBACrD,OAAO,CAAC,IAAI,CACV,kCAAkC,IAAI,uCAAuC,IAAI,+CAA+C,IAAI,EAAE,CACvI,CAAC;gBAEF,IAAI,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ;oBACxB,OAAO,CAAC,GAAG,CAAC,GAAG,gBAAgB,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YAC7D,CAAC,CACF,CAAC;QAEJ,OAAO,IAAI,CAAC;IACd,CAAC;CAAA;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;QAChB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\nlet _arkosConfig: ArkosConfig = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: 8000,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port)\n server = _app.listen(\n arkosConfig?.host ? [port, arkosConfig?.host!] : port,\n () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n );\n\n if (!!process.env.NODE_ENV)\n console.log(`${`Environment: ${process.env.NODE_ENV}`}`);\n }\n );\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n server.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /** Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * Defines jwt configurations for secret, expiresIn, cookieExpiresIn\n *\n * Can be pass also through env variables:\n * - jwt.secret => JWT_SECRET: If not passed production auth will not work\n * - jwt.expiresIn => JWT_EXPIRES_IN: default 30d\n * - jwt.cookieExpiresIn => JWT_COOKIE_EXPIRES_IN: default 90\n */\n jwt?: {\n /** Secret to sign and decode jwt tokens */\n secret?: string;\n /** */\n expiresIn?: string;\n /** Days in which the cookie must be kept before expire*/\n cookieExpiresIn?: number;\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n uploadRestrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n others?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: RateLimitOptions;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additionals?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additionals?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /** Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * Defines jwt configurations for secret, expiresIn, cookieExpiresIn\n *\n * Can be pass also through env variables:\n * - jwt.secret => JWT_SECRET: If not passed production auth will not work\n * - jwt.expiresIn => JWT_EXPIRES_IN: default 30d\n * - jwt.cookieExpiresIn => JWT_COOKIE_EXPIRES_IN: default 90\n */\n jwt?: {\n /** Secret to sign and decode jwt tokens */\n secret?: string;\n /** */\n expiresIn?: string;\n /** Days in which the cookie must be kept before expire*/\n cookieExpiresIn?: number;\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n others?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: RateLimitOptions;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additionals?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additionals?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * Email used for auth as well as sending emails\n */\n from: string;\n /**\n * Your SMTP password\n */\n password: string;\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Possible actions that can be performed by a controller.\n */\nexport type ControllerActions = \"create\" | \"update\" | \"delete\" | \"view\";\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AccessControlRules = {\n /**\n * Maps each `ControllerAction` to the roles allowed to perform it.\n */\n [key in ControllerActions]: any | any[];\n};\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AuthenticationControlRules = {\n /**\n * Maps each `ControllerAction` to the actions that requires authentication to perform it.\n */\n [key in ControllerActions]: boolean;\n};\n\n/**\n * Configuration for authentication and access control.\n */\nexport type AuthConfigs = {\n /**\n * Defines access control rules for roles or actions.\n *\n * @type {Role | Role[] | AccessControlRules}\n */\n authenticationControl?: boolean | Partial<AuthenticationControlRules>;\n accessControl?: any | any[] | Partial<AccessControlRules>;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n */\nexport interface AuthJwtPayload extends JwtPayload {\n /**\n * The unique identifier of the authenticated user.\n *\n * @type {number | string}\n */\n id?: number | string;\n\n /**\n * The username of the authenticated user.\n *\n * @type {string}\n */\n username?: string;\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Possible actions that can be performed by a controller.\n */\nexport type ControllerActions = \"create\" | \"update\" | \"delete\" | \"view\";\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AccessControlRules = {\n /**\n * Maps each `ControllerAction` to the roles allowed to perform it.\n */\n [key in ControllerActions]: any[];\n};\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AuthenticationControlRules = {\n /**\n * Maps each `ControllerAction` to the actions that requires authentication to perform it.\n */\n [key in ControllerActions]: boolean;\n};\n\n/**\n * Configuration for authentication and access control.\n */\nexport type AuthConfigs = {\n /**\n * Defines access control rules for roles or actions.\n *\n * @type {Role | Role[] | AccessControlRules}\n */\n authenticationControl?: boolean | Partial<AuthenticationControlRules>;\n /**\n * List of user roles, or restricted by actions\n */\n accessControl?: any[] | Partial<AccessControlRules>;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n */\nexport interface AuthJwtPayload extends JwtPayload {\n /**\n * The unique identifier of the authenticated user.\n *\n * @type {number | string}\n */\n id?: number | string;\n\n /**\n * The username of the authenticated user.\n *\n * @type {string}\n */\n username?: string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AAuCA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { Prisma } from \"@prisma/client\";\nimport { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T> = {\n queryOptions?: Omit<\n Prisma.Args<T, \"findMany\">,\n \"where\" | \"cursor\" | \"take\" | \"skip\" | \"orderBy\"\n >;\n findOne?: Partial<Partial<Prisma.Args<T, \"findUnique\">>>;\n findMany?: Partial<Prisma.Args<T, \"findMany\">>;\n deleteMany?: Partial<Prisma.Args<T, \"deleteMany\">>;\n updateMany?: Partial<Prisma.Args<T, \"updateMany\">>;\n createMany?: Partial<Prisma.Args<T, \"createMany\">>;\n createOne?: Partial<Prisma.Args<T, \"create\">>;\n updateOne?: Partial<Prisma.Args<T, \"update\">>;\n deleteOne?: Partial<Prisma.Args<T, \"delete\">>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n create = \"create\",\n view = \"view\",\n update = \"update\",\n delete = \"delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AAuCA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { Prisma } from \"@prisma/client\";\nimport { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T> = {\n queryOptions?: Omit<\n Prisma.Args<T, \"findMany\">,\n \"where\" | \"cursor\" | \"take\" | \"skip\" | \"orderBy\"\n >;\n findOne?: Partial<Partial<Prisma.Args<T, \"findUnique\">>>;\n findMany?: Partial<Prisma.Args<T, \"findMany\">>;\n deleteMany?: Partial<Prisma.Args<T, \"deleteMany\">>;\n updateMany?: Partial<Prisma.Args<T, \"updateMany\">>;\n createMany?: Partial<Prisma.Args<T, \"createMany\">>;\n createOne?: Partial<Prisma.Args<T, \"create\">>;\n updateOne?: Partial<Prisma.Args<T, \"update\">>;\n deleteOne?: Partial<Prisma.Args<T, \"delete\">>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n create = \"create\",\n view = \"view\",\n update = \"update\",\n delete = \"delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
@@ -194,11 +194,24 @@ const schemaFolderPath = process.env.PRISMA_SCHEMA_PATH || arkos_env_1.default.P
194
194
  const prismaModelRelationFields = {};
195
195
  exports.prismaModelRelationFields = prismaModelRelationFields;
196
196
  const prismaContent = [];
197
- const files = fs_1.default
198
- .readdirSync(schemaFolderPath)
199
- .filter((file) => file.endsWith(".prisma"));
197
+ function getAllPrismaFiles(dirPath, fileList = []) {
198
+ const files = fs_1.default.readdirSync(dirPath);
199
+ files === null || files === void 0 ? void 0 : files.forEach((file) => {
200
+ const filePath = path_1.default.join(dirPath, file);
201
+ const stat = fs_1.default.statSync(filePath);
202
+ if (stat.isDirectory() && file !== "migrations") {
203
+ fileList = getAllPrismaFiles(filePath, fileList);
204
+ }
205
+ else if (stat.isFile() && file.endsWith(".prisma")) {
206
+ fileList.push(filePath);
207
+ }
208
+ });
209
+ return fileList;
210
+ }
211
+ const prismaRootDir = "./prisma";
212
+ const files = getAllPrismaFiles(prismaRootDir);
200
213
  for (const file of files) {
201
- const filePath = path_1.default.join(schemaFolderPath, file);
214
+ const filePath = path_1.default.join(prismaRootDir, file);
202
215
  const stats = fs_1.default.statSync(filePath);
203
216
  if (stats.isFile()) {
204
217
  const content = fs_1.default.readFileSync(filePath, "utf-8");
@@ -218,7 +231,7 @@ for (const model of models) {
218
231
  const modelName = (0, change_case_helpers_1.pascalCase)(model);
219
232
  let modelFile;
220
233
  for (const file of files) {
221
- const filePath = path_1.default.join(schemaFolderPath, file);
234
+ const filePath = path_1.default.join(prismaRootDir, file);
222
235
  const stats = fs_1.default.statSync(filePath);
223
236
  if (stats.isFile()) {
224
237
  const content = fs_1.default.readFileSync(filePath, "utf-8");
@@ -232,7 +245,7 @@ for (const model of models) {
232
245
  if (!modelFile) {
233
246
  throw new Error(`Model ${modelName} not found`);
234
247
  }
235
- const content = fs_1.default.readFileSync(path_1.default.join(schemaFolderPath, modelFile), "utf-8");
248
+ const content = fs_1.default.readFileSync(path_1.default.join(prismaRootDir, modelFile), "utf-8");
236
249
  const modelStart = content.indexOf(`model ${modelName} {`);
237
250
  const modelEnd = content.indexOf("}", modelStart);
238
251
  const modelDefinition = content.slice(modelStart, modelEnd);
@@ -1 +1 @@
1
- {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAEC;AASD,4DAoNC;AAgKD,0DAIC;AAmBgB,8BAAS;AAAE,oDAAoB;AArahD,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6DAAoC;AACpC,6CAAiD;AAEjD,MAAM,mBAAmB,GAGrB,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AASD,SAAsB,wBAAwB,CAAC,SAAiB;;QAC9D,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QAC5C,MAAM,cAAc,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC;QAE/C,MAAM,SAAS,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;QAC3E,MAAM,OAAO,GAAG,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAC7C,MAAM,UAAU,GAAG,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;QAEnD,MAAM,eAAe,GAAG,cAAI,CAAC,IAAI,CAC/B,SAAS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gBACvB,SAAS,KAAK,UAAU;gBACxB,SAAS,KAAK,OAAO;gBACrB,SAAS,KAAK,SAAS;gBACvB,SAAS,KAAK,QAAQ;gBACtB,SAAS,KAAK,MAAM,EACpB,CAAC;gBACD,SAAS;YACX,CAAC;YAED,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EAAE,CAAC;gBAC1B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;oBACtB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;iBAAM,CAAC;gBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;oBAClB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACnD,CAAC;AACH,CAAC;AAQD,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAClC,IAAI,CAAC,CAAC,SAAS,IAAI,yBAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,MAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,wBAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport arkosEnv from \"../arkos-env\";\nimport { userFileExtension } from \"./fs.helpers\";\n\nconst prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\n/**\n * Dynamically imports model-specific modules like middlewares, auth configurations,\n * prisma query options, and DTOs for a given model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\").\n * @returns {Promise<Object>} An object containing the imported modules: `middlewares`, `authConfigs`, `prismaQueryOptions`, and `dtos`.\n */\nexport async function importPrismaModelModules(modelName: string) {\n const kebabModelName = kebabCase(modelName);\n const lowerModelName = modelName.toLowerCase();\n\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n const dtosDir = path.join(moduleDir, \"dtos\");\n const schemasDir = path.join(moduleDir, \"schemas\");\n\n const middlewaresFile = path.join(\n moduleDir,\n `${kebabModelName}.middlewares.${userFileExtension}`\n );\n const authConfigsFile = path.join(\n moduleDir,\n `${kebabModelName}.auth-configs.${userFileExtension}`\n );\n const prismaQueryOptionsFile = path.join(\n moduleDir,\n `${kebabModelName}.prisma-query-options.${userFileExtension}`\n );\n\n // Define DTO file paths\n const modelDtoFile = path.join(\n dtosDir,\n `${lowerModelName}.dto.${userFileExtension}`\n );\n const createDtoFile = path.join(\n dtosDir,\n `create-${lowerModelName}.dto.${userFileExtension}`\n );\n const updateDtoFile = path.join(\n dtosDir,\n `update-${lowerModelName}.dto.${userFileExtension}`\n );\n const queryDtoFile = path.join(\n dtosDir,\n `query-${lowerModelName}.dto.${userFileExtension}`\n );\n\n const modelSchemaFile = path.join(\n schemasDir,\n `${lowerModelName}.schema.${userFileExtension}`\n );\n const createSchemaFile = path.join(\n schemasDir,\n `create-${lowerModelName}.schema.${userFileExtension}`\n );\n const updateSchemaFile = path.join(\n schemasDir,\n `update-${lowerModelName}.schema.${userFileExtension}`\n );\n const querySchemaFile = path.join(\n schemasDir,\n `query-${lowerModelName}.schema.${userFileExtension}`\n );\n\n const result: {\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n dtos: {\n create?: any;\n update?: any;\n query?: any;\n model?: any;\n };\n schemas: {\n create?: any;\n update?: any;\n query?: any;\n model?: any;\n };\n } = {\n dtos: {},\n schemas: {},\n };\n\n try {\n if (fs.existsSync(middlewaresFile)) {\n const middlewareModule = await import(middlewaresFile);\n result.middlewares = middlewareModule;\n }\n } catch (error) {\n console.error(\n `Error importing middlewares for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(authConfigsFile)) {\n const authConfigsModule = await import(authConfigsFile);\n result.authConfigs = authConfigsModule.default || authConfigsModule;\n }\n } catch (error) {\n console.error(\n `Error importing auth configs for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(prismaQueryOptionsFile)) {\n const prismaQueryOptionsModule = await import(prismaQueryOptionsFile);\n result.prismaQueryOptions =\n prismaQueryOptionsModule.default || prismaQueryOptionsModule;\n }\n } catch (error) {\n console.error(\n `Error importing prisma query options for model \"${modelName}\":`,\n error\n );\n }\n\n // Import DTOs\n const pascalModelName = pascalCase(modelName);\n try {\n if (fs.existsSync(modelDtoFile)) {\n const modelDtoModule = await import(modelDtoFile);\n result.dtos.model =\n modelDtoModule.default || modelDtoModule[`${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing model main DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(createDtoFile)) {\n const createDtoModule = await import(createDtoFile);\n result.dtos.create =\n createDtoModule.default ||\n createDtoModule[`Create${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing create DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(updateDtoFile)) {\n const updateDtoModule = await import(updateDtoFile);\n result.dtos.update =\n updateDtoModule.default ||\n updateDtoModule[`Update${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing update DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(queryDtoFile)) {\n const queryDtoModule = await import(queryDtoFile);\n result.dtos.query =\n queryDtoModule.default || queryDtoModule[`Query${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(`Error importing query DTO for model \"${modelName}\":`, error);\n }\n\n try {\n if (fs.existsSync(createSchemaFile)) {\n const createSchemaModule = await import(createSchemaFile);\n result.dtos.create =\n createSchemaModule.default ||\n createSchemaModule[`Create${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing create Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(updateSchemaFile)) {\n const updateSchemaModule = await import(updateSchemaFile);\n result.dtos.update =\n updateSchemaModule.default ||\n updateSchemaModule[`Update${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing update Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(querySchemaFile)) {\n const querySchemaModule = await import(querySchemaFile);\n result.dtos.query =\n querySchemaModule.default ||\n querySchemaModule[`Query${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing query Schema for model \"${modelName}\":`,\n error\n );\n }\n\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\nconst schemaFolderPath =\n process.env.PRISMA_SCHEMA_PATH || arkosEnv.PRISMA_SCHEMA_PATH;\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nconst prismaModelRelationFields: Record<string, RelationFields> = {};\n\nconst prismaContent: string[] = [];\n\nconst files = fs\n .readdirSync(schemaFolderPath)\n .filter((file) => file.endsWith(\".prisma\"));\n\nfor (const file of files) {\n const filePath = path.join(schemaFolderPath, file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n }\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nconst models: string[] = [];\nconst prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nprismaContent.join(\"\\n\").replace(modelRegex, (_, modelName) => {\n if (!models.includes(modelName)) models.push(camelCase(modelName.trim()));\n return modelName;\n});\n\nfor (const model of models) {\n const modelName = pascalCase(model);\n\n let modelFile;\n for (const file of files) {\n const filePath = path.join(schemaFolderPath, file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n if (content.includes(`model ${modelName} {`)) {\n modelFile = file;\n break;\n }\n }\n }\n\n if (!modelFile) {\n throw new Error(`Model ${modelName} not found`);\n }\n\n const content = fs.readFileSync(\n path.join(schemaFolderPath, modelFile),\n \"utf-8\"\n );\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine.includes(\"@unique\");\n\n if (isUnique)\n prismaModelsUniqueFields[model] = [\n ...(prismaModelsUniqueFields[model] || []),\n { name: fieldName, type, isUnique },\n ];\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine.includes(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models.includes(camelCase(cleanType || \"\"))\n ) {\n const modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n ) {\n continue;\n }\n\n if (!type?.includes(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n}\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { models, getModels, getModelUniqueFields, prismaModelRelationFields };\n"]}
1
+ {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAEC;AASD,4DAoNC;AA8KD,0DAIC;AAmBgB,8BAAS;AAAE,oDAAoB;AAnbhD,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6DAAoC;AACpC,6CAAiD;AAEjD,MAAM,mBAAmB,GAGrB,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAA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AK,OAAO;gBACrB,SAAS,KAAK,SAAS;gBACvB,SAAS,KAAK,QAAQ;gBACtB,SAAS,KAAK,MAAM,EACpB,CAAC;gBACD,SAAS;YACX,CAAC;YAED,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EAAE,CAAC;gBAC1B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;oBACtB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;iBAAM,CAAC;gBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;oBAClB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACnD,CAAC;AACH,CAAC;AAQD,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAClC,IAAI,CAAC,CAAC,SAAS,IAAI,yBAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,MAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,wBAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport arkosEnv from \"../arkos-env\";\nimport { userFileExtension } from \"./fs.helpers\";\n\nconst prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\n/**\n * Dynamically imports model-specific modules like middlewares, auth configurations,\n * prisma query options, and DTOs for a given model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\").\n * @returns {Promise<Object>} An object containing the imported modules: `middlewares`, `authConfigs`, `prismaQueryOptions`, and `dtos`.\n */\nexport async function importPrismaModelModules(modelName: string) {\n const kebabModelName = kebabCase(modelName);\n const lowerModelName = modelName.toLowerCase();\n\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n const dtosDir = path.join(moduleDir, \"dtos\");\n const schemasDir = path.join(moduleDir, \"schemas\");\n\n const middlewaresFile = path.join(\n moduleDir,\n `${kebabModelName}.middlewares.${userFileExtension}`\n );\n const authConfigsFile = path.join(\n moduleDir,\n `${kebabModelName}.auth-configs.${userFileExtension}`\n );\n const prismaQueryOptionsFile = path.join(\n moduleDir,\n `${kebabModelName}.prisma-query-options.${userFileExtension}`\n );\n\n // Define DTO file paths\n const modelDtoFile = path.join(\n dtosDir,\n `${lowerModelName}.dto.${userFileExtension}`\n );\n const createDtoFile = path.join(\n dtosDir,\n `create-${lowerModelName}.dto.${userFileExtension}`\n );\n const updateDtoFile = path.join(\n dtosDir,\n `update-${lowerModelName}.dto.${userFileExtension}`\n );\n const queryDtoFile = path.join(\n dtosDir,\n `query-${lowerModelName}.dto.${userFileExtension}`\n );\n\n const modelSchemaFile = path.join(\n schemasDir,\n `${lowerModelName}.schema.${userFileExtension}`\n );\n const createSchemaFile = path.join(\n schemasDir,\n `create-${lowerModelName}.schema.${userFileExtension}`\n );\n const updateSchemaFile = path.join(\n schemasDir,\n `update-${lowerModelName}.schema.${userFileExtension}`\n );\n const querySchemaFile = path.join(\n schemasDir,\n `query-${lowerModelName}.schema.${userFileExtension}`\n );\n\n const result: {\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n dtos: {\n create?: any;\n update?: any;\n query?: any;\n model?: any;\n };\n schemas: {\n create?: any;\n update?: any;\n query?: any;\n model?: any;\n };\n } = {\n dtos: {},\n schemas: {},\n };\n\n try {\n if (fs.existsSync(middlewaresFile)) {\n const middlewareModule = await import(middlewaresFile);\n result.middlewares = middlewareModule;\n }\n } catch (error) {\n console.error(\n `Error importing middlewares for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(authConfigsFile)) {\n const authConfigsModule = await import(authConfigsFile);\n result.authConfigs = authConfigsModule.default || authConfigsModule;\n }\n } catch (error) {\n console.error(\n `Error importing auth configs for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(prismaQueryOptionsFile)) {\n const prismaQueryOptionsModule = await import(prismaQueryOptionsFile);\n result.prismaQueryOptions =\n prismaQueryOptionsModule.default || prismaQueryOptionsModule;\n }\n } catch (error) {\n console.error(\n `Error importing prisma query options for model \"${modelName}\":`,\n error\n );\n }\n\n // Import DTOs\n const pascalModelName = pascalCase(modelName);\n try {\n if (fs.existsSync(modelDtoFile)) {\n const modelDtoModule = await import(modelDtoFile);\n result.dtos.model =\n modelDtoModule.default || modelDtoModule[`${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing model main DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(createDtoFile)) {\n const createDtoModule = await import(createDtoFile);\n result.dtos.create =\n createDtoModule.default ||\n createDtoModule[`Create${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing create DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(updateDtoFile)) {\n const updateDtoModule = await import(updateDtoFile);\n result.dtos.update =\n updateDtoModule.default ||\n updateDtoModule[`Update${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing update DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(queryDtoFile)) {\n const queryDtoModule = await import(queryDtoFile);\n result.dtos.query =\n queryDtoModule.default || queryDtoModule[`Query${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(`Error importing query DTO for model \"${modelName}\":`, error);\n }\n\n try {\n if (fs.existsSync(createSchemaFile)) {\n const createSchemaModule = await import(createSchemaFile);\n result.dtos.create =\n createSchemaModule.default ||\n createSchemaModule[`Create${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing create Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(updateSchemaFile)) {\n const updateSchemaModule = await import(updateSchemaFile);\n result.dtos.update =\n updateSchemaModule.default ||\n updateSchemaModule[`Update${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing update Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(querySchemaFile)) {\n const querySchemaModule = await import(querySchemaFile);\n result.dtos.query =\n querySchemaModule.default ||\n querySchemaModule[`Query${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing query Schema for model \"${modelName}\":`,\n error\n );\n }\n\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\nconst schemaFolderPath =\n process.env.PRISMA_SCHEMA_PATH || arkosEnv.PRISMA_SCHEMA_PATH;\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nconst prismaModelRelationFields: Record<string, RelationFields> = {};\n\nconst prismaContent: string[] = [];\n\nfunction getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst prismaRootDir = \"./prisma\"; // Adjust this path if needed\nconst files = getAllPrismaFiles(prismaRootDir);\n\nfor (const file of files) {\n const filePath = path.join(prismaRootDir, file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n }\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nconst models: string[] = [];\nconst prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nprismaContent.join(\"\\n\").replace(modelRegex, (_, modelName) => {\n if (!models.includes(modelName)) models.push(camelCase(modelName.trim()));\n return modelName;\n});\n\nfor (const model of models) {\n const modelName = pascalCase(model);\n\n let modelFile;\n for (const file of files) {\n const filePath = path.join(prismaRootDir, file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n if (content.includes(`model ${modelName} {`)) {\n modelFile = file;\n break;\n }\n }\n }\n\n if (!modelFile) {\n throw new Error(`Model ${modelName} not found`);\n }\n\n const content = fs.readFileSync(path.join(prismaRootDir, modelFile), \"utf-8\");\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine.includes(\"@unique\");\n\n if (isUnique)\n prismaModelsUniqueFields[model] = [\n ...(prismaModelsUniqueFields[model] || []),\n { name: fieldName, type, isUnique },\n ];\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine.includes(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models.includes(camelCase(cleanType || \"\"))\n ) {\n const modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n ) {\n continue;\n }\n\n if (!type?.includes(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n}\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { models, getModels, getModelUniqueFields, prismaModelRelationFields };\n"]}
@@ -1 +1 @@
1
- "use strict";var R=function(e,f,u,n){function c(t){return t instanceof u?t:new u(function(o){o(t)})}return new(u||(u=Promise))(function(t,o){function d(l){try{s(n.next(l))}catch(r){o(r)}}function p(l){try{s(n.throw(l))}catch(r){o(r)}}function s(l){l.done?t(l.value):c(l.value).then(d,p)}s((n=n.apply(e,f||[])).next())})};import P from"express";import q from"cors";import E from"cookie-parser";import{getAuthRouter as A}from"./modules/auth/auth.router";import{getPrismaModelsRouter as O,getAvailableResourcesAndRoutesRouter as _}from"./modules/base/base.router";import H from"./modules/error-handler/error-handler.controller";import{rateLimit as M}from"express-rate-limit";import v from"path";import*as T from"dotenv";import x from"compression";import{handleRequestLogs as L}from"./modules/base/base.middlewares";import{checkDatabaseConnection as U,loadPrismaModule as b}from"./utils/helpers/prisma.helpers";import{getFileUploaderRouter as N}from"./modules/file-upload/file-upload.router";import{queryParser as j}from"./utils/helpers/query-parser.helpers";import y from"./utils/helpers/deepmerge.helper";const m=process.env.NODE_ENV;let a=".env";m==="production"?a=v.resolve(process.cwd(),".env.production"):m==="staging"?a=v.resolve(process.cwd(),".env.staging"):m==="development"?a=v.resolve(process.cwd(),".env.development"):m==="local"?a=v.resolve(process.cwd(),".env.local"):m==="test"?a=v.resolve(process.cwd(),".env.test"):m==="qa"&&(a=v.resolve(process.cwd(),".env.qa")),T.config({path:a});const i=P();R(void 0,void 0,void 0,function*(){yield b()});export function bootstrap(e){return R(this,void 0,void 0,function*(){var f,u,n;yield b(),e.configureApp&&(yield e.configureApp(i));const c=e?.middlewares,t=c?.disable||[],o=c?.replace||{};t.includes("compression")||i.use(o.compression||x(e?.compressionOptions)),t.includes("global-rate-limit")||i.use(o.globalRateLimit||M(y({windowMs:60*1e3,limit:1e3,standardHeaders:"draft-7",legacyHeaders:!1},e?.globalRequestRateLimitOptions||{}))),t.includes("cors")||i.use(o.cors||q(!((f=e?.cors)===null||f===void 0)&&f.customHandler?e.cors.customHandler:y({origin:(l,r)=>{var h;const w=(h=e?.cors)===null||h===void 0?void 0:h.allowedOrigins;w==="*"?r(null,!0):Array.isArray(w)?r(null,!l||w.includes(l)):typeof w=="string"?r(null,!l||w===l):r(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},((u=e?.cors)===null||u===void 0?void 0:u.options)||{}))),t.includes("express-json")||i.use(o.expressJson||P.json(e?.jsonBodyParserOptions)),t.includes("cookie-parser")||i.use(o.cookieParser||E(...e?.cookieParserParameters||[])),t.includes("query-parser")||i.use(o.queryParser||j(y({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),t.includes("database-connection")||i.use(o.databaseConnection||U),t.includes("request-logger")||i.use(o.requestLogger||L),!((n=e?.middlewares)===null||n===void 0)&&n.additionals&&e.middlewares.additionals.forEach(l=>{i.use(l)});const d=e?.routers,p=d?.disable||[],s=d?.replace||{};if(p.includes("welcome-endpoint")||i.get("/api",s.welcomeEndpoint||((l,r)=>{r.status(200).json({message:e.welcomeMessage})})),!p.includes("file-uploader")){const l=s.fileUploader?yield s.fileUploader(e):yield N(e);i.use("/api",l)}if(!p.includes("auth-router")&&e.authentication){const l=s.authRouter?yield s.authRouter(e):yield A(e);i.use("/api",l)}if(!p.includes("prisma-models-router")){const l=s.prismaModelsRouter?yield s.prismaModelsRouter(e):yield O();i.use("/api",l)}return i.use("/api",_()),d?.additionals&&d.additionals.forEach(l=>{i.use(l)}),t.includes("global-error-handler")||i.use(o.globalErrorHandler||H),i})}
1
+ "use strict";var P=function(e,f,u,n){function c(t){return t instanceof u?t:new u(function(o){o(t)})}return new(u||(u=Promise))(function(t,o){function d(l){try{s(n.next(l))}catch(r){o(r)}}function p(l){try{s(n.throw(l))}catch(r){o(r)}}function s(l){l.done?t(l.value):c(l.value).then(d,p)}s((n=n.apply(e,f||[])).next())})};import R from"express";import b from"cors";import q from"cookie-parser";import{getAuthRouter as E}from"./modules/auth/auth.router";import{getPrismaModelsRouter as A,getAvailableResourcesAndRoutesRouter as O}from"./modules/base/base.router";import _ from"./modules/error-handler/error-handler.controller";import{rateLimit as H}from"express-rate-limit";import v from"path";import*as M from"dotenv";import T from"compression";import{handleRequestLogs as x}from"./modules/base/base.middlewares";import{checkDatabaseConnection as L,loadPrismaModule as U}from"./utils/helpers/prisma.helpers";import{getFileUploaderRouter as N}from"./modules/file-uploader/file-uploader.router";import{queryParser as j}from"./utils/helpers/query-parser.helpers";import y from"./utils/helpers/deepmerge.helper";const m=process.env.NODE_ENV;let a=".env";m==="production"?a=v.resolve(process.cwd(),".env.production"):m==="staging"?a=v.resolve(process.cwd(),".env.staging"):m==="development"?a=v.resolve(process.cwd(),".env.development"):m==="local"?a=v.resolve(process.cwd(),".env.local"):m==="test"?a=v.resolve(process.cwd(),".env.test"):m==="qa"&&(a=v.resolve(process.cwd(),".env.qa")),M.config({path:a});const i=R();export function bootstrap(e){return P(this,void 0,void 0,function*(){var f,u,n;yield U(),e.configureApp&&(yield e.configureApp(i));const c=e?.middlewares,t=c?.disable||[],o=c?.replace||{};t.includes("compression")||i.use(o.compression||T(e?.compressionOptions)),t.includes("global-rate-limit")||i.use(o.globalRateLimit||H(y({windowMs:60*1e3,limit:1e3,standardHeaders:"draft-7",legacyHeaders:!1},e?.globalRequestRateLimitOptions||{}))),t.includes("cors")||i.use(o.cors||b(!((f=e?.cors)===null||f===void 0)&&f.customHandler?e.cors.customHandler:y({origin:(l,r)=>{var h;const w=(h=e?.cors)===null||h===void 0?void 0:h.allowedOrigins;w==="*"?r(null,!0):Array.isArray(w)?r(null,!l||w.includes(l)):typeof w=="string"?r(null,!l||w===l):r(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},((u=e?.cors)===null||u===void 0?void 0:u.options)||{}))),t.includes("express-json")||i.use(o.expressJson||R.json(e?.jsonBodyParserOptions)),t.includes("cookie-parser")||i.use(o.cookieParser||q(...e?.cookieParserParameters||[])),t.includes("query-parser")||i.use(o.queryParser||j(y({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),t.includes("database-connection")||i.use(o.databaseConnection||L),t.includes("request-logger")||i.use(o.requestLogger||x),!((n=e?.middlewares)===null||n===void 0)&&n.additionals&&e.middlewares.additionals.forEach(l=>{i.use(l)});const d=e?.routers,p=d?.disable||[],s=d?.replace||{};if(p.includes("welcome-endpoint")||i.get("/api",s.welcomeEndpoint||((l,r)=>{r.status(200).json({message:e.welcomeMessage})})),!p.includes("file-uploader")){const l=s.fileUploader?yield s.fileUploader(e):yield N(e);i.use("/api",l)}if(!p.includes("auth-router")&&e.authentication){const l=s.authRouter?yield s.authRouter(e):yield E(e);i.use("/api",l)}if(!p.includes("prisma-models-router")){const l=s.prismaModelsRouter?yield s.prismaModelsRouter(e):yield A();i.use("/api",l)}return i.use("/api",O()),d?.additionals&&d.additionals.forEach(l=>{i.use(l)}),t.includes("global-error-handler")||i.use(o.globalErrorHandler||_),i})}
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE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GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAChC,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;QAGxD,IAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,WAAW,EAAE,CAAC;YAC/B,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;gBAC3C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC;QAGD,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,sBAAsB,CAAC;YACvD,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;QAElE,OAAO,GAAG,CAAC;IACb,CAAC;CAAA","sourcesContent":["import express 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 path from \"path\";\nimport * as dotenv from \"dotenv\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } 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\";\n\nconst ENV = process.env.NODE_ENV;\nlet envPath = \".env\";\n\n// Default to `.env.local` if available in any environment\nif (ENV === \"production\") {\n envPath = path.resolve(process.cwd(), \".env.production\");\n} else if (ENV === \"staging\") {\n envPath = path.resolve(process.cwd(), \".env.staging\");\n} else if (ENV === \"development\") {\n envPath = path.resolve(process.cwd(), \".env.development\");\n} else if (ENV === \"local\") {\n // For local development, .env.local can be used\n envPath = path.resolve(process.cwd(), \".env.local\");\n}\n\n// Optionally, add support for `.env.test`, `.env.qa`, or other environments if required\nelse if (ENV === \"test\") {\n envPath = path.resolve(process.cwd(), \".env.test\");\n} else if (ENV === \"qa\") {\n envPath = path.resolve(process.cwd(), \".env.qa\");\n}\n\ndotenv.config({ path: envPath });\n\nconst app = express();\n\n(async () => {\n await loadPrismaModule();\n})();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares.includes(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares.includes(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\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 // JSON body parser middleware\n if (!disabledMiddlewares.includes(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares.includes(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\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 // Database connection check middleware\n if (!disabledMiddlewares.includes(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares.includes(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additionals)\n arkosConfig.middlewares.additionals.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters.includes(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters.includes(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(\"/api\", fileUploaderRouter);\n }\n\n // Auth router\n if (!disabledRouters.includes(\"auth-router\") && arkosConfig.authentication) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters.includes(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter();\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additionals) {\n routersConfig.additionals.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\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":";;;;;;;;;AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC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M,EAAE,oCAAoC,EAAE,CAAC,CAAC;QAGxD,IAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,WAAW,EAAE,CAAC;YAC/B,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;gBAC3C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC;QAGD,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,sBAAsB,CAAC;YACvD,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;QAElE,OAAO,GAAG,CAAC;IACb,CAAC;CAAA","sourcesContent":["import express 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 path from \"path\";\nimport * as dotenv from \"dotenv\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nconst ENV = process.env.NODE_ENV;\nlet envPath = \".env\";\n\n// Default to `.env.local` if available in any environment\nif (ENV === \"production\") {\n envPath = path.resolve(process.cwd(), \".env.production\");\n} else if (ENV === \"staging\") {\n envPath = path.resolve(process.cwd(), \".env.staging\");\n} else if (ENV === \"development\") {\n envPath = path.resolve(process.cwd(), \".env.development\");\n} else if (ENV === \"local\") {\n // For local development, .env.local can be used\n envPath = path.resolve(process.cwd(), \".env.local\");\n}\n\n// Optionally, add support for `.env.test`, `.env.qa`, or other environments if required\nelse if (ENV === \"test\") {\n envPath = path.resolve(process.cwd(), \".env.test\");\n} else if (ENV === \"qa\") {\n envPath = path.resolve(process.cwd(), \".env.qa\");\n}\n\ndotenv.config({ path: envPath });\n\nconst app = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares.includes(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares.includes(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\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 // JSON body parser middleware\n if (!disabledMiddlewares.includes(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares.includes(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\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 // Database connection check middleware\n if (!disabledMiddlewares.includes(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares.includes(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additionals)\n arkosConfig.middlewares.additionals.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters.includes(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters.includes(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(\"/api\", fileUploaderRouter);\n }\n\n // Auth router\n if (!disabledRouters.includes(\"auth-router\") && arkosConfig.authentication) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters.includes(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter();\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additionals) {\n routersConfig.additionals.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares.includes(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getFileUploaderServices, FileUploaderService, } from "./../../modules/file-upload/file-upload.service";
1
+ import { getFileUploaderServices, FileUploaderService, } from "../../modules/file-uploader/file-uploader.service";
2
2
  import authService from "../../modules/auth/auth.service";
3
3
  import emailService, { EmailService } from "../../modules/email/email.service";
4
4
  import { BaseService, getBaseServices } from "../../modules/base/base.service";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/exports/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,mBAAmB,GACpB,MAAM,iDAAiD,CAAC;AAEzD,OAAO,WAAW,MAAM,iCAAiC,CAAC;AAC1D,OAAO,YAAY,EAAE,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAK/E,OAAO,EAAE,WAAW,EAAE,CAAC;AAKvB,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,CAAC;AAKxC,OAAO,EAAE,YAAY,EAAE,YAAY,EAAgB,CAAC;AAKpD,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import {\n getFileUploaderServices,\n FileUploaderService,\n} from \"./../../modules/file-upload/file-upload.service\";\nimport { EmailOptions } from \"../../modules/email/email.service\";\nimport authService from \"../../modules/auth/auth.service\";\nimport emailService, { EmailService } from \"../../modules/email/email.service\";\nimport { BaseService, getBaseServices } from \"../../modules/base/base.service\";\n\n/**\n * Authentication service.\n */\nexport { authService };\n\n/**\n * Base service.\n */\nexport { BaseService, getBaseServices };\n\n/**\n * Email service.\n */\nexport { emailService, EmailService, EmailOptions };\n\n/**\n * File upload services.\n */\nexport { getFileUploaderServices, FileUploaderService };\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/exports/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,mBAAmB,GACpB,MAAM,mDAAmD,CAAC;AAE3D,OAAO,WAAW,MAAM,iCAAiC,CAAC;AAC1D,OAAO,YAAY,EAAE,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAK/E,OAAO,EAAE,WAAW,EAAE,CAAC;AAKvB,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,CAAC;AAKxC,OAAO,EAAE,YAAY,EAAE,YAAY,EAAgB,CAAC;AAKpD,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import {\n getFileUploaderServices,\n FileUploaderService,\n} from \"../../modules/file-uploader/file-uploader.service\";\nimport { EmailOptions } from \"../../modules/email/email.service\";\nimport authService from \"../../modules/auth/auth.service\";\nimport emailService, { EmailService } from \"../../modules/email/email.service\";\nimport { BaseService, getBaseServices } from \"../../modules/base/base.service\";\n\n/**\n * Authentication service.\n */\nexport { authService };\n\n/**\n * Base service.\n */\nexport { BaseService, getBaseServices };\n\n/**\n * Email service.\n */\nexport { emailService, EmailService, EmailOptions };\n\n/**\n * File upload services.\n */\nexport { getFileUploaderServices, FileUploaderService };\n"]}
@@ -73,18 +73,39 @@ class AuthService {
73
73
  }
74
74
  handleActionAccessControl(authConfigs, action, modelName) {
75
75
  return catchAsync((req, res, next) => __awaiter(this, void 0, void 0, function* () {
76
+ var _a, _b, _c, _d;
76
77
  if (req.user) {
77
78
  const user = req.user;
78
79
  const prisma = getPrismaInstance();
79
- const permissions = yield prisma.authPermission.count({
80
- where: {
81
- resource: kebabCase(singular(modelName)),
82
- action,
83
- roleId: { in: user.roles.map((role) => role.roleId) },
84
- },
85
- });
86
- if (!permissions) {
87
- return next(new AppError("You do not have permission to perfom this action", 403));
80
+ const configs = getArkosConfig();
81
+ if (user.isSuperUser) {
82
+ next();
83
+ return;
84
+ }
85
+ if (((_a = configs === null || configs === void 0 ? void 0 : configs.authentication) === null || _a === void 0 ? void 0 : _a.mode) === "dynamic") {
86
+ const permissions = yield prisma.authPermission.count({
87
+ where: {
88
+ resource: kebabCase(singular(modelName)),
89
+ action,
90
+ roleId: { in: user.roles.map((role) => role.roleId) },
91
+ },
92
+ });
93
+ if (!permissions)
94
+ return next(new AppError("You do not have permission to perfom this action", 403));
95
+ }
96
+ else if (((_b = configs === null || configs === void 0 ? void 0 : configs.authentication) === null || _b === void 0 ? void 0 : _b.mode) === "static") {
97
+ const accessControl = authConfigs === null || authConfigs === void 0 ? void 0 : authConfigs.accessControl;
98
+ let authorizedRoles = [];
99
+ if (accessControl) {
100
+ if (Array.isArray(accessControl))
101
+ authorizedRoles = accessControl;
102
+ else if (accessControl[action])
103
+ authorizedRoles = accessControl[action];
104
+ if (!authorizedRoles.includes((_c = req.user) === null || _c === void 0 ? void 0 : _c.role) ||
105
+ (((_d = req.user) === null || _d === void 0 ? void 0 : _d.roles).length > 0 &&
106
+ !(authorizedRoles === null || authorizedRoles === void 0 ? void 0 : authorizedRoles.some((role) => { var _a; return ((_a = req.user) === null || _a === void 0 ? void 0 : _a.roles).includes(role); }))))
107
+ return next(new AppError("You do not have permission to perfom this action", 403));
108
+ }
88
109
  }
89
110
  }
90
111
  next();
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[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AEJ,IACE,IAAI,CAAC,wBAAwB,CAAC,IAAI,EAAE,OAAO,CAAC,GAAI,CAAC;gBACjD,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBAE5B,MAAM,IAAI,QAAQ,CAChB,sDAAsD,EACtD,GAAG,CACJ,CAAC;YAEJ,OAAO,IAAI,CAAC;QACd,CAAC;KAAA;IA+BD,2BAA2B,CACzB,WAAoC,EACpC,MAAyB,EACzB,SAAiB;QAEjB,MAAM,qBAAqB,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,qBAAqB,CAAC;QAEjE,IAAI,qBAAqB,IAAI,OAAO,qBAAqB,KAAK,QAAQ,EAAE,CAAC;YACvE,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,KAAK;gBAAE,OAAO,QAAQ,CAAC;iBACxD,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,IAAI;gBAAE,OAAO,IAAI,CAAC,YAAY,CAAC;QAC5E,CAAC;;YAAM,OAAO,IAAI,CAAC,YAAY,CAAC;QAEhC,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User, UserRole } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthConfigs,\n AuthJwtPayload,\n ControllerActions,\n} from \"../../types/auth\";\nimport { kebabCase } from \"../../utils/helpers/change-case.helpers\";\nimport { singular } from \"pluralize\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nclass AuthService {\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn: string | number = process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN,\n secret: string = process.env.JWT_SECRET || arkosEnv.JWT_SECRET\n ): string {\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as any,\n });\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret: string = process.env.JWT_SECRET || arkosEnv.JWT_SECRET\n ): Promise<AuthJwtPayload> {\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AuthConfigs} authConfigs - The configuration object for authentication and access control.\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} modelName - The model name that the action is being performed on (e.g., \"User\", \"Post\").\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleActionAccessControl(\n authConfigs: AuthConfigs,\n action: ControllerActions,\n modelName: string\n ): ArkosRequestHandler {\n return catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.user) {\n const user = req.user as any;\n const prisma = getPrismaInstance();\n\n const permissions = await (prisma as any).authPermission.count({\n where: {\n resource: kebabCase(singular(modelName)),\n action,\n roleId: { in: user.roles.map((role: UserRole) => role.roleId) },\n },\n });\n\n if (!permissions) {\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401\n );\n\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n include: {\n roles: {\n include: {\n role: {\n include: {\n permissions: true,\n },\n },\n },\n },\n },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path.includes(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401\n );\n\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {AuthConfigs | undefined} authConfigs - The authentication configuration object.\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} modelName - The model name being affected by the action.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n authConfigs: AuthConfigs | undefined,\n action: ControllerActions,\n modelName: string\n ): ArkosRequestHandler {\n const authenticationControl = authConfigs?.authenticationControl;\n\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,GAAG,MAAM,cAAc,CAAC;AAC/B,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAYvE,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAKrC,MAAM,WAAW;IAAjB;QA8QE,iBAAY,GAAG,UAAU,CACvB,CAAO,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM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,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User, UserRole } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthConfigs,\n AuthJwtPayload,\n ControllerActions,\n} from \"../../types/auth\";\nimport { kebabCase } from \"../../utils/helpers/change-case.helpers\";\nimport { singular } from \"pluralize\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nclass AuthService {\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn: string | number = process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN,\n secret: string = process.env.JWT_SECRET || arkosEnv.JWT_SECRET\n ): string {\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as any,\n });\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret: string = process.env.JWT_SECRET || arkosEnv.JWT_SECRET\n ): Promise<AuthJwtPayload> {\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AuthConfigs} authConfigs - The configuration object for authentication and access control.\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} modelName - The model name that the action is being performed on (e.g., \"User\", \"Post\").\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleActionAccessControl(\n authConfigs: AuthConfigs,\n action: ControllerActions,\n modelName: string\n ): ArkosRequestHandler {\n return catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.user) {\n const user = req.user as any;\n const prisma = getPrismaInstance();\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const permissions = await (prisma as any).authPermission.count({\n where: {\n resource: kebabCase(singular(modelName)),\n action,\n roleId: { in: user.roles.map((role: UserRole) => role.roleId) },\n },\n });\n\n if (!permissions)\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n } else if (configs?.authentication?.mode === \"static\") {\n const accessControl = authConfigs?.accessControl;\n let authorizedRoles: any[] = [];\n\n if (accessControl) {\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action];\n\n // Checks for both cases if using single role or multiple roles\n if (\n !authorizedRoles.includes(req.user?.role) ||\n ((req.user?.roles as any[]).length > 0 &&\n !authorizedRoles?.some((role) =>\n (req.user?.roles as any[]).includes(role)\n ))\n )\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n }\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401\n );\n\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n include: {\n roles: {\n include: {\n role: {\n include: {\n permissions: true,\n },\n },\n },\n },\n },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path.includes(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401\n );\n\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {AuthConfigs | undefined} authConfigs - The authentication configuration object.\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} modelName - The model name being affected by the action.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n authConfigs: AuthConfigs | undefined,\n action: ControllerActions,\n modelName: string\n ): ArkosRequestHandler {\n const authenticationControl = authConfigs?.authenticationControl;\n\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}