arkos 1.1.44-test → 1.1.45-test

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.
@@ -15,6 +15,7 @@ function setupRouters(models, router, arkosConfigs) {
15
15
  const modelNameInKebab = (0, utils_1.kebabCase)(model);
16
16
  const modelModules = await (0, models_helpers_1.importPrismaModelModules)(modelNameInKebab);
17
17
  const { middlewares, authConfigs, prismaQueryOptions, router: customRouterModule, dtos, schemas, } = modelModules;
18
+ console.log(modelNameInKebab, JSON.stringify(modelModules, null, 2));
18
19
  const routeName = (0, pluralize_1.plural)(modelNameInKebab);
19
20
  const controller = new base_controller_1.BaseController(model);
20
21
  const routerConfig = customRouterModule?.config;
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAeA,oCAuVC;AArWD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAEhC,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,MAAM,SAAS,GAAG,IAAA,kBAAM,EAAC,gBAAgB,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,IAAI,gCAAc,CAAC,KAAK,CAAC,CAAC;QAG7C,MAAM,YAAY,GAAiB,kBAAkB,EAAE,MAAM,CAA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,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;QACJ,CAAC;QAGD,IAAI,kBAAkB,EAAE,OAAO,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YACxE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;gBACnC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;oBAChB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;oBAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;oBAExB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;wBACjC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,WAAW,EAAS,CAAC;wBAGtD,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;wBAGnE,MAAc,CAAC,MAAM,CAAC,CAAC,IAAI,SAAS,IAAI,IAAI,EAAE,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAChE,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n customRouter.stack.forEach((layer) => {\n if (layer.route) {\n const route = layer.route;\n const path = route.path;\n\n route.stack.forEach((routeLayer) => {\n const method = routeLayer.method.toLowerCase() as any;\n\n // Get all middleware handlers for this route\n const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // Apply all middleware handlers to the matching route method\n (router as any)[method](`/${routeName}/${path}`, ...handlers);\n });\n }\n });\n }\n });\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAeA,oCAyVC;AAvWD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAEhC,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAAC,YAAY,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W,EAAE,eAAe,IAAI,UAAU,CAAC,SAAS,EACpD,WAAW,EAAE,eAAe;gBAC1B,CAAC,CAAC,UAAU,CAAC,SAAS;gBACtB,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,+BAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;QACJ,CAAC;QAGD,IAAI,kBAAkB,EAAE,OAAO,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YACxE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;gBACnC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;oBAChB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;oBAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;oBAExB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;wBACjC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,WAAW,EAAS,CAAC;wBAGtD,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;wBAGnE,MAAc,CAAC,MAAM,CAAC,CAAC,IAAI,SAAS,IAAI,IAAI,EAAE,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAChE,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n console.log(modelNameInKebab, JSON.stringify(modelModules, null, 2));\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n customRouter.stack.forEach((layer) => {\n if (layer.route) {\n const route = layer.route;\n const path = route.path;\n\n route.stack.forEach((routeLayer) => {\n const method = routeLayer.method.toLowerCase() as any;\n\n // Get all middleware handlers for this route\n const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // Apply all middleware handlers to the matching route method\n (router as any)[method](`/${routeName}/${path}`, ...handlers);\n });\n }\n });\n }\n });\n}\n"]}
package/dist/cjs/proxy.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(r,e,o,t){t===void 0&&(t=o);var n=Object.getOwnPropertyDescriptor(e,o);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[o]}}),Object.defineProperty(r,t,n)}:function(r,e,o,t){t===void 0&&(t=o),r[t]=e[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),__importStar=this&&this.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(o){var t=[];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(t[t.length]=n);return t},r(e)};return function(e){if(e&&e.__esModule)return e;var o={};if(e!=null)for(var t=r(e),n=0;n<t.length;n++)t[n]!=="default"&&__createBinding(o,e,t[n]);return __setModuleDefault(o,e),o}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.arkosProxy=void 0,exports.getCapturedConfig=getCapturedConfig;let capturedConfig=null;exports.arkosProxy={init:r=>(capturedConfig=r,Promise.resolve().then(()=>__importStar(require("../path/to/real/arkos"))).then(e=>e.initApp(r)))};function getCapturedConfig(){return capturedConfig}
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(r,e,i,t){t===void 0&&(t=i);var n=Object.getOwnPropertyDescriptor(e,i);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(r,t,n)}:function(r,e,i,t){t===void 0&&(t=i),r[t]=e[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),__importStar=this&&this.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(i){var t=[];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[t.length]=n);return t},r(e)};return function(e){if(e&&e.__esModule)return e;var i={};if(e!=null)for(var t=r(e),n=0;n<t.length;n++)t[n]!=="default"&&__createBinding(i,e,t[n]);return __setModuleDefault(i,e),i}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.arkosProxy=void 0,exports.getCapturedConfig=getCapturedConfig;let capturedConfig=null;exports.arkosProxy={init:r=>(capturedConfig=r,Promise.resolve().then(()=>__importStar(require("../path/to/real/arkos"))).then(e=>e.initApp(r)))};function getCapturedConfig(){return capturedConfig}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport 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\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\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 /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for pass prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\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 /**\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 * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\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 allowedUsernames?: string[];\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 /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\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 * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\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 files?: {\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 *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\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?: Partial<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 additional?: 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 additional?: 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/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/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 * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => 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 * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport 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\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\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 /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\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 /**\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 * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\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 allowedUsernames?: string[];\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 /**\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 *@see 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 * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\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 files?: {\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 *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\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?: Partial<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 additional?: 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 additional?: 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/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/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 * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => 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 * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -57,7 +57,6 @@ function getModelModules(modelName) {
57
57
  }
58
58
  function getFileModelModulesFileStructure(modelName) {
59
59
  const kebabModelName = (0, change_case_helpers_1.kebabCase)(modelName).toLowerCase();
60
- const lowerModelName = kebabModelName.toLowerCase();
61
60
  const isAuthModule = modelName.toLowerCase() === "auth";
62
61
  const ext = (0, fs_helpers_1.getUserFileExtension)();
63
62
  return {
@@ -77,12 +76,12 @@ function getFileModelModulesFileStructure(modelName) {
77
76
  updatePassword: `update-password.dto.${ext}`,
78
77
  }
79
78
  : {
80
- model: `${lowerModelName}.dto.${ext}`,
81
- create: `create-${lowerModelName}.dto.${ext}`,
82
- createMany: `create-many-${lowerModelName}.dto.${ext}`,
83
- update: `update-${lowerModelName}.dto.${ext}`,
84
- updateMany: `update-many-${lowerModelName}.dto.${ext}`,
85
- query: `query-${lowerModelName}.dto.${ext}`,
79
+ model: `${kebabModelName}.dto.${ext}`,
80
+ create: `create-${kebabModelName}.dto.${ext}`,
81
+ createMany: `create-many-${kebabModelName}.dto.${ext}`,
82
+ update: `update-${kebabModelName}.dto.${ext}`,
83
+ updateMany: `update-many-${kebabModelName}.dto.${ext}`,
84
+ query: `query-${kebabModelName}.dto.${ext}`,
86
85
  },
87
86
  schemas: isAuthModule
88
87
  ? {
@@ -92,12 +91,12 @@ function getFileModelModulesFileStructure(modelName) {
92
91
  updatePassword: `update-password.schema.${ext}`,
93
92
  }
94
93
  : {
95
- model: `${lowerModelName}.schema.${ext}`,
96
- create: `create-${lowerModelName}.schema.${ext}`,
97
- createMany: `create-many-${lowerModelName}.schema.${ext}`,
98
- update: `update-${lowerModelName}.schema.${ext}`,
99
- updateMany: `update-many-${lowerModelName}.schema.${ext}`,
100
- query: `query-${lowerModelName}.schema.${ext}`,
94
+ model: `${kebabModelName}.schema.${ext}`,
95
+ create: `create-${kebabModelName}.schema.${ext}`,
96
+ createMany: `create-many-${kebabModelName}.schema.${ext}`,
97
+ update: `update-${kebabModelName}.schema.${ext}`,
98
+ updateMany: `update-many-${kebabModelName}.schema.${ext}`,
99
+ query: `query-${kebabModelName}.schema.${ext}`,
101
100
  },
102
101
  };
103
102
  }
@@ -137,7 +136,7 @@ async function processSubdir(modelName, type, result) {
137
136
  }
138
137
  }
139
138
  async function importPrismaModelModules(modelName) {
140
- const moduleDir = path_1.default.resolve((0, fs_helpers_1.crd)(), "src", "modules", modelName);
139
+ const moduleDir = path_1.default.resolve((0, fs_helpers_1.crd)(), "src", "modules", (0, change_case_helpers_1.kebabCase)(modelName));
141
140
  const result = {
142
141
  dtos: {},
143
142
  schemas: {},
@@ -1 +1 @@
1
- {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,0CAEC;AAED,4EA8CC;AAED,sCAmDC;AAoBD,4DAkCC;AA2BD,8CAgBC;AAOD,wDA4GC;AAUD,0DAKC;AAmBQ,8BAAS;AAAE,oDAAoB;AA7WxC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAyD;AACzD,qDAAgD;AAGrC,QAAA,mBAAmB,GAG1B,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,2BAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS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ED,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC5B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,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 { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${lowerModelName}.dto.${ext}`,\n create: `create-${lowerModelName}.dto.${ext}`,\n createMany: `create-many-${lowerModelName}.dto.${ext}`,\n update: `update-${lowerModelName}.dto.${ext}`,\n updateMany: `update-many-${lowerModelName}.dto.${ext}`,\n query: `query-${lowerModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${lowerModelName}.schema.${ext}`,\n create: `create-${lowerModelName}.schema.${ext}`,\n createMany: `create-many-${lowerModelName}.schema.${ext}`,\n update: `update-${lowerModelName}.schema.${ext}`,\n updateMany: `update-many-${lowerModelName}.schema.${ext}`,\n query: `query-${lowerModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", modelName);\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\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\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function 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 modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\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 const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\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 enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 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 // && !content.includes?.(`model ${cleanType} {`)\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\ninitializePrismaModels();\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\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 { getModels, getModelUniqueFields };\n"]}
1
+ {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,0CAEC;AAED,4EA6CC;AAED,sCAmDC;AAoBD,4DAkCC;AA2BD,8CAgBC;AAOD,wDA4GC;AAUD,0DAKC;AAmBQ,8BAAS;AAAE,oDAAoB;AA5WxC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAyD;AACzD,qDAAgD;AAGrC,QAAA,mBAAmB,GAG1B,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,2BAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxD,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IAEnC,OAAO;QACL,IAAI,EAAE;YACJ,OAAO,EAAE,GAAG,cAAc,YAAY,GAAG,EAAE;YAC3C,UAAU,EAAE,GAAG,cAAc,eAAe,GAAG,EAAE;YACjD,WAAW,EAAE,GA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CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,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 { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\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\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function 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 modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\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 const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\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 enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 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 // && !content.includes?.(`model ${cleanType} {`)\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\ninitializePrismaModels();\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\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 { getModels, getModelUniqueFields };\n"]}
@@ -9,6 +9,7 @@ export function setupRouters(models, router, arkosConfigs) {
9
9
  const modelNameInKebab = kebabCase(model);
10
10
  const modelModules = await importPrismaModelModules(modelNameInKebab);
11
11
  const { middlewares, authConfigs, prismaQueryOptions, router: customRouterModule, dtos, schemas, } = modelModules;
12
+ console.log(modelNameInKebab, JSON.stringify(modelModules, null, 2));
12
13
  const routeName = plural(modelNameInKebab);
13
14
  const controller = new BaseController(model);
14
15
  const routerConfig = customRouterModule?.config;
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAGtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,wBAAwB,CAAC;AAEhC,MAAM,UAAU,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,wBAAwB,CAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,MAAM,SAAS,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,IAAI,cAAc,CAA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,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;gBACnC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;oBAChB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;oBAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;oBAExB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;wBACjC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,WAAW,EAAS,CAAC;wBAGtD,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;wBAGnE,MAAc,CAAC,MAAM,CAAC,CAAC,IAAI,SAAS,IAAI,IAAI,EAAE,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAChE,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n customRouter.stack.forEach((layer) => {\n if (layer.route) {\n const route = layer.route;\n const path = route.path;\n\n route.stack.forEach((routeLayer) => {\n const method = routeLayer.method.toLowerCase() as any;\n\n // Get all middleware handlers for this route\n const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // Apply all middleware handlers to the matching route method\n (router as any)[method](`/${routeName}/${path}`, ...handlers);\n });\n }\n });\n }\n });\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAGtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,wBAAwB,CAAC;AAEhC,MAAM,UAAU,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,wBAAwB,CAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,OAAO,CAAC,GAAG,CAAC,gBAAgB,EA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EAAE,cAAc;gBAC7B,CAAC,CAAC,YAAY,EAChB,YAAY,CACb,CAAC;QACJ,CAAC;QAGD,IAAI,kBAAkB,EAAE,OAAO,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YACxE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;gBACnC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;oBAChB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;oBAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;oBAExB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;wBACjC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,WAAW,EAAS,CAAC;wBAGtD,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;wBAGnE,MAAc,CAAC,MAAM,CAAC,CAAC,IAAI,SAAS,IAAI,IAAI,EAAE,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAChE,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n console.log(modelNameInKebab, JSON.stringify(modelModules, null, 2));\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n customRouter.stack.forEach((layer) => {\n if (layer.route) {\n const route = layer.route;\n const path = route.path;\n\n route.stack.forEach((routeLayer) => {\n const method = routeLayer.method.toLowerCase() as any;\n\n // Get all middleware handlers for this route\n const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // Apply all middleware handlers to the matching route method\n (router as any)[method](`/${routeName}/${path}`, ...handlers);\n });\n }\n });\n }\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport 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\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\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 /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for pass prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\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 /**\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 * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\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 allowedUsernames?: string[];\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 /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\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 * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\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 files?: {\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 *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\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?: Partial<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 additional?: 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 additional?: 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/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/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 * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => 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 * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport 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\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\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 /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\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 /**\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 * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\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 allowedUsernames?: string[];\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 /**\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 *@see 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 * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\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 files?: {\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 *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\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?: Partial<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 additional?: 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 additional?: 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/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/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 * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => 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 * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -9,7 +9,6 @@ export function getModelModules(modelName) {
9
9
  }
10
10
  export function getFileModelModulesFileStructure(modelName) {
11
11
  const kebabModelName = kebabCase(modelName).toLowerCase();
12
- const lowerModelName = kebabModelName.toLowerCase();
13
12
  const isAuthModule = modelName.toLowerCase() === "auth";
14
13
  const ext = getUserFileExtension();
15
14
  return {
@@ -29,12 +28,12 @@ export function getFileModelModulesFileStructure(modelName) {
29
28
  updatePassword: `update-password.dto.${ext}`,
30
29
  }
31
30
  : {
32
- model: `${lowerModelName}.dto.${ext}`,
33
- create: `create-${lowerModelName}.dto.${ext}`,
34
- createMany: `create-many-${lowerModelName}.dto.${ext}`,
35
- update: `update-${lowerModelName}.dto.${ext}`,
36
- updateMany: `update-many-${lowerModelName}.dto.${ext}`,
37
- query: `query-${lowerModelName}.dto.${ext}`,
31
+ model: `${kebabModelName}.dto.${ext}`,
32
+ create: `create-${kebabModelName}.dto.${ext}`,
33
+ createMany: `create-many-${kebabModelName}.dto.${ext}`,
34
+ update: `update-${kebabModelName}.dto.${ext}`,
35
+ updateMany: `update-many-${kebabModelName}.dto.${ext}`,
36
+ query: `query-${kebabModelName}.dto.${ext}`,
38
37
  },
39
38
  schemas: isAuthModule
40
39
  ? {
@@ -44,12 +43,12 @@ export function getFileModelModulesFileStructure(modelName) {
44
43
  updatePassword: `update-password.schema.${ext}`,
45
44
  }
46
45
  : {
47
- model: `${lowerModelName}.schema.${ext}`,
48
- create: `create-${lowerModelName}.schema.${ext}`,
49
- createMany: `create-many-${lowerModelName}.schema.${ext}`,
50
- update: `update-${lowerModelName}.schema.${ext}`,
51
- updateMany: `update-many-${lowerModelName}.schema.${ext}`,
52
- query: `query-${lowerModelName}.schema.${ext}`,
46
+ model: `${kebabModelName}.schema.${ext}`,
47
+ create: `create-${kebabModelName}.schema.${ext}`,
48
+ createMany: `create-many-${kebabModelName}.schema.${ext}`,
49
+ update: `update-${kebabModelName}.schema.${ext}`,
50
+ updateMany: `update-many-${kebabModelName}.schema.${ext}`,
51
+ query: `query-${kebabModelName}.schema.${ext}`,
53
52
  },
54
53
  };
55
54
  }
@@ -89,7 +88,7 @@ export async function processSubdir(modelName, type, result) {
89
88
  }
90
89
  }
91
90
  export async function importPrismaModelModules(modelName) {
92
- const moduleDir = path.resolve(crd(), "src", "modules", modelName);
91
+ const moduleDir = path.resolve(crd(), "src", "modules", kebabCase(modelName));
93
92
  const result = {
94
93
  dtos: {},
95
94
  schemas: {},
@@ -1 +1 @@
1
- {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAGhD,MAAM,CAAC,IAAI,mBAAmB,GAG1B,EAAE,CAAC;AAEP,MAAM,UAAU,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAAmB,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,UAAU,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,cAAc,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC;IACpD,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxD,MAAM,GAAG,GAAG,oBAAoB,EAAE,CAAC;IAEnC,OAAO;QACL,IAAI,EAAE;YACJ,OAAO,EAAE,GAAG,cAAc,YAAY,GAAG,EAAE;YAC3C,UAAU,EAAE,GAAG,cAAc,eAAe,GAAG,EAAE;YACjD,WAAW,EAAE,GAAG,cAAc,gBAAgB,GAAG,EAAE;YACnD,WAAW,EAAE,GAAG,cAAc,iBAAiB,GAAG,EAAE;YACpD,kBAAkB,EAAE,GAAG,cAAc,yBAAyB,GAAG,EAAE;YACnE,MAAM,EAAE,GAAG,cAAc,WAAW,GAAG,EAAE;SAC1C;QACD,IAAI,EAAE,YAAY;YAChB,CAAC,CAAC;gBACE,KAAK,EAAE,aAA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,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;AAED,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,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 { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${lowerModelName}.dto.${ext}`,\n create: `create-${lowerModelName}.dto.${ext}`,\n createMany: `create-many-${lowerModelName}.dto.${ext}`,\n update: `update-${lowerModelName}.dto.${ext}`,\n updateMany: `update-many-${lowerModelName}.dto.${ext}`,\n query: `query-${lowerModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${lowerModelName}.schema.${ext}`,\n create: `create-${lowerModelName}.schema.${ext}`,\n createMany: `create-many-${lowerModelName}.schema.${ext}`,\n update: `update-${lowerModelName}.schema.${ext}`,\n updateMany: `update-many-${lowerModelName}.schema.${ext}`,\n query: `query-${lowerModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", modelName);\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\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\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function 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 modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\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 const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\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 enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 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 // && !content.includes?.(`model ${cleanType} {`)\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\ninitializePrismaModels();\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\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 { getModels, getModelUniqueFields };\n"]}
1
+ {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACL,S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EAAE,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 { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\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\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function 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 modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\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 const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\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 enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 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 // && !content.includes?.(`model ${cleanType} {`)\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\ninitializePrismaModels();\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\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 { getModels, getModelUniqueFields };\n"]}
@@ -22,7 +22,6 @@ export type ArkosConfig = {
22
22
  allowedUsernames?: string[];
23
23
  sendAccessTokenThrough?: "cookie-only" | "response-only" | "both";
24
24
  };
25
- usernameField?: string;
26
25
  passwordValidation?: {
27
26
  regex: RegExp;
28
27
  message?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkos",
3
- "version": "1.1.44-test",
3
+ "version": "1.1.45-test",
4
4
  "description": "The Express & Prisma Framework For RESTful API",
5
5
  "main": "dist/cjs/exports/index.js",
6
6
  "module": "dist/es2020/exports/index.js",