arkos 1.4.0-canary.54 → 1.4.0-canary.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/app.js +2 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/class-validator-to-json-schema.js +16 -0
- package/dist/cjs/modules/swagger/utils/helpers/class-validator-to-json-schema.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +1 -2
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js.map +1 -1
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +1 -2
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/route-config-validator.js +5 -5
- package/dist/cjs/utils/arkos-router/route-config-validator.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/app.js +2 -1
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/class-validator-to-json-schema.js +13 -0
- package/dist/esm/modules/swagger/utils/helpers/class-validator-to-json-schema.js.map +1 -0
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +1 -2
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js.map +1 -1
- package/dist/esm/server.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +1 -2
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/route-config-validator.js +5 -5
- package/dist/esm/utils/arkos-router/route-config-validator.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/types/modules/swagger/utils/helpers/class-validator-to-json-schema.d.ts +1 -0
- package/dist/types/types/new-arkos-config.d.ts +1 -1
- package/package.json +1 -1
package/dist/cjs/app.js
CHANGED
|
@@ -180,7 +180,8 @@ async function bootstrap(initConfig) {
|
|
|
180
180
|
}
|
|
181
181
|
const fileUploadRouter = (0, file_upload_router_1.getFileUploadRouter)(arkosConfig);
|
|
182
182
|
knowModulesRouter.use(fileUploadRouter);
|
|
183
|
-
if (arkosConfig.authentication
|
|
183
|
+
if (arkosConfig.authentication &&
|
|
184
|
+
arkosConfig.authentication?.enabled !== false) {
|
|
184
185
|
const authRouter = (0, auth_router_1.getAuthRouter)(arkosConfig);
|
|
185
186
|
knowModulesRouter.use("/api", authRouter);
|
|
186
187
|
}
|
package/dist/cjs/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,8BA+LC;AAxND,mDAAmD;AACnD,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAAkE;AAClE,iFAA+E;AAC/E,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AACpE,2DAAiE;AACjE,2DAAmD;AACnD,2FAAkE;AAClE,uCAA2C;AAE9B,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAC9C,MAAM,iBAAiB,GAAG,IAAA,gBAAM,GAAE,CAAC;AAE5B,KAAK,UAAU,SAAS,CAC7B,UAA2B;IAE3B,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;IAErC,MAAM,OAAO,CAAC,GAAG,CAAC;QAChB,IAAA,iCAAgB,GAAE;QAClB,IAAA,wCAAuB,EAAC,WAAW,CAAC;QACpC,UAAU,EAAE,YAAY,IAAI,CAAC,MAAM,UAAU,EAAE,YAAY,CAAC,WAAG,CAAC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,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC3B,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAA,kDAAoC,GAAE,CAAC,CAAC;IAExD,IACE,WAAW,CAAC,OAAO;QACnB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YACjC,WAAW,CAAC,OAAO,CAAC,gBAAgB,KAAK,IAAI,CAAC;QAEhD,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,IAAA,iCAAgB,EAAC,WAAW,EAAE,WAAG,CAAC,CAAC,CAAC;IAE5D,WAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,IAAI,wBAAQ,CAChB,iBAAiB,EACjB,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,EACnB,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,WAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,WAAG,CAAC,GAAG,CAAC,kCAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n if (typeof middlewaresConfig?.cors === \"function\") {\n app.use(middlewaresConfig.cors);\n } else {\n app.use(\n cors(\n middlewaresConfig?.cors?.customHandler\n ? middlewaresConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = (middlewaresConfig?.cors as any)\n ?.allowedOrigins;\n\n if (allowed === \"*\") cb(null, true);\n else if (Array.isArray(allowed))\n cb(null, !origin || allowed?.includes?.(origin));\n else if (typeof allowed === \"string\")\n cb(null, !origin || allowed === origin);\n else cb(null, false);\n },\n\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n middlewaresConfig?.cors?.options || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params = Array.isArray(middlewaresConfig?.cookieParser)\n ? middlewaresConfig.cookieParser\n : [];\n app.use(cookieParser(...(params as any))); // FIXME: check types correctly\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (arkosConfig.authentication) {\n const authRouter = getAuthRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.path },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,8BAkMC;AA3ND,mDAAmD;AACnD,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAAkE;AAClE,iFAA+E;AAC/E,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AACpE,2DAAiE;AACjE,2DAAmD;AACnD,2FAAkE;AAClE,uCAA2C;AAE9B,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAC9C,MAAM,iBAAiB,GAAG,IAAA,gBAAM,GAAE,CAAC;AAE5B,KAAK,UAAU,SAAS,CAC7B,UAA2B;IAE3B,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;IA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AC,CAAC;QAC9C,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAC5C,CAAC;IAED,MAAM,YAAY,GAAG,IAAA,mCAAqB,EAAC,WAAW,CAAC,CAAC;IACxD,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAE5C,WAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC3B,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAA,kDAAoC,GAAE,CAAC,CAAC;IAExD,IACE,WAAW,CAAC,OAAO;QACnB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YACjC,WAAW,CAAC,OAAO,CAAC,gBAAgB,KAAK,IAAI,CAAC;QAEhD,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,IAAA,iCAAgB,EAAC,WAAW,EAAE,WAAG,CAAC,CAAC,CAAC;IAE5D,WAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,IAAI,wBAAQ,CAChB,iBAAiB,EACjB,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,EACnB,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,WAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,WAAG,CAAC,GAAG,CAAC,kCAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n if (typeof middlewaresConfig?.cors === \"function\") {\n app.use(middlewaresConfig.cors);\n } else {\n app.use(\n cors(\n middlewaresConfig?.cors?.customHandler\n ? middlewaresConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = (middlewaresConfig?.cors as any)\n ?.allowedOrigins;\n\n if (allowed === \"*\") cb(null, true);\n else if (Array.isArray(allowed))\n cb(null, !origin || allowed?.includes?.(origin));\n else if (typeof allowed === \"string\")\n cb(null, !origin || allowed === origin);\n else cb(null, false);\n },\n\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n middlewaresConfig?.cors?.options || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params = Array.isArray(middlewaresConfig?.cookieParser)\n ? middlewaresConfig.cookieParser\n : [];\n app.use(cookieParser(...(params as any))); // FIXME: check types correctly\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (\n arkosConfig.authentication &&\n arkosConfig.authentication?.enabled !== false\n ) {\n const authRouter = getAuthRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.path },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = classValidatorToJsonSchema;
|
|
4
|
+
const class_validator_1 = require("class-validator");
|
|
5
|
+
const class_validator_jsonschema_1 = require("class-validator-jsonschema");
|
|
6
|
+
const global_helpers_1 = require("../../../../utils/helpers/global.helpers");
|
|
7
|
+
async function classValidatorToJsonSchema(decoratedClass) {
|
|
8
|
+
const { defaultMetadataStorage } = await (0, global_helpers_1.importModule)("class-transformer/cjs/storage.js");
|
|
9
|
+
const jsonSchemas = (0, class_validator_jsonschema_1.validationMetadatasToSchemas)({
|
|
10
|
+
classValidatorMetadataStorage: (0, class_validator_1.getMetadataStorage)(),
|
|
11
|
+
classTransformerMetadataStorage: defaultMetadataStorage,
|
|
12
|
+
refPointerPrefix: "#/components/schemas/",
|
|
13
|
+
});
|
|
14
|
+
return jsonSchemas[decoratedClass.name];
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=class-validator-to-json-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"class-validator-to-json-schema.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/class-validator-to-json-schema.ts"],"names":[],"mappings":";;AAIA,6CAcC;AAlBD,qDAAqD;AACrD,2EAA0E;AAC1E,6EAAwE;AAEzD,KAAK,UAAU,0BAA0B,CACtD,cAA8C;IAE9C,MAAM,EAAE,sBAAsB,EAAE,GAAG,MAAM,IAAA,6BAAY,EACnD,kCAAkC,CACnC,CAAC;IAEF,MAAM,WAAW,GAAG,IAAA,yDAA4B,EAAC;QAC/C,6BAA6B,EAAE,IAAA,oCAAkB,GAAE;QACnD,+BAA+B,EAAE,sBAAsB;QACvD,gBAAgB,EAAE,uBAAuB;KAC1C,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import { getMetadataStorage } from \"class-validator\";\nimport { validationMetadatasToSchemas } from \"class-validator-jsonschema\";\nimport { importModule } from \"../../../../utils/helpers/global.helpers\";\n\nexport default async function classValidatorToJsonSchema(\n decoratedClass: new (...args: any[]) => object\n): Promise<any> {\n const { defaultMetadataStorage } = await importModule(\n \"class-transformer/cjs/storage.js\"\n );\n\n const jsonSchemas = validationMetadatasToSchemas({\n classValidatorMetadataStorage: getMetadataStorage(),\n classTransformerMetadataStorage: defaultMetadataStorage,\n refPointerPrefix: \"#/components/schemas/\",\n });\n\n return jsonSchemas[decoratedClass.name];\n}\n"]}
|
|
@@ -31,9 +31,8 @@ async function generateClassValidatorJsonSchemas() {
|
|
|
31
31
|
if (dtoClass && !ignoredDtoTypes.includes(dtoType.toLowerCase())) {
|
|
32
32
|
try {
|
|
33
33
|
const schemaName = (0, swagger_router_helpers_1.getCorrectJsonSchemaName)(dtoType, modelName, "Dto");
|
|
34
|
-
if (schemas[schemaName])
|
|
34
|
+
if (schemas[schemaName])
|
|
35
35
|
throw Error(`Found more then 1 ${dtoClass.name} classes among your .dto.${(0, fs_helpers_1.getUserFileExtension)()} files, there is no way to correctly generate json-schemas for swagger documentation.`);
|
|
36
|
-
}
|
|
37
36
|
schemas[schemaName] = jsonSchema[dtoClass.name] || {};
|
|
38
37
|
}
|
|
39
38
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-class-validator-json-schemas.js","sourceRoot":"","sources":["../../../../../../../src/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.ts"],"names":[],"mappings":";;;;;AAQA,
|
|
1
|
+
{"version":3,"file":"generate-class-validator-json-schemas.js","sourceRoot":"","sources":["../../../../../../../src/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.ts"],"names":[],"mappings":";;;;;AAQA,8EAmDC;AA3DD,2EAA0E;AAC1E,gFAA2E;AAC3E,qDAAqD;AACrD,wEAA0E;AAC1E,sEAAqE;AACrE,4GAAkF;AAClF,wEAA+E;AAExE,KAAK,UAAU,iCAAiC;IACrD,MAAM,kBAAkB,GAAG;QACzB,GAAG,8BAAkB,CAAC,yBAAyB,EAAE;QACjD,MAAM;KACP,CAAC;IACF,MAAM,OAAO,GAAwB,EAAE,CAAC;IAExC,MAAM,EAAE,sBAAsB,EAAE,GAAG,MAAM,IAAA,6BAAY,EACnD,kCAAkC,CACnC,CAAC;IAEF,MAAM,UAAU,GAAG,IAAA,yDAA4B,EAAC;QAC9C,6BAA6B,EAAE,IAAA,oCAAkB,GAA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SAAS,CAAC;YAAE,OAAO,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC;IACvD,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { validationMetadatasToSchemas } from \"class-validator-jsonschema\";\nimport { importModule } from \"../../../../../utils/helpers/global.helpers\";\nimport { getMetadataStorage } from \"class-validator\";\nimport { getModuleComponents } from \"../../../../../utils/dynamic-loader\";\nimport { getCorrectJsonSchemaName } from \"../swagger.router.helpers\";\nimport prismaSchemaParser from \"../../../../../utils/prisma/prisma-schema-parser\";\nimport { getUserFileExtension } from \"../../../../../utils/helpers/fs.helpers\";\n\nexport async function generateClassValidatorJsonSchemas() {\n const requiredAppModules = [\n ...prismaSchemaParser.getModelsAsArrayOfStrings(),\n \"auth\",\n ];\n const schemas: Record<string, any> = {};\n\n const { defaultMetadataStorage } = await importModule(\n \"class-transformer/cjs/storage.js\"\n );\n\n const jsonSchema = validationMetadatasToSchemas({\n classValidatorMetadataStorage: getMetadataStorage(),\n classTransformerMetadataStorage: defaultMetadataStorage,\n refPointerPrefix: \"#/components/schemas/\",\n });\n\n requiredAppModules.forEach((modelName) => {\n const moduleComponents = getModuleComponents(modelName);\n\n if (moduleComponents?.dtos) {\n Object.entries(moduleComponents.dtos).forEach(([dtoType, dtoClass]) => {\n const ignoredDtoTypes = [\"createone\", \"updateone\"];\n if (dtoClass && !ignoredDtoTypes.includes(dtoType.toLowerCase())) {\n try {\n const schemaName = getCorrectJsonSchemaName(\n dtoType,\n modelName,\n \"Dto\"\n );\n\n if (schemas[schemaName])\n throw Error(\n `Found more then 1 ${dtoClass.name} classes among your .dto.${getUserFileExtension()} files, there is no way to correctly generate json-schemas for swagger documentation.`\n );\n\n schemas[schemaName] = jsonSchema[dtoClass.name] || {};\n } catch (err: any) {\n throw new Error(\n `Failed to generate schema for ${dtoType} ${modelName}: ${err.message}`\n );\n }\n }\n });\n }\n });\n\n Object.entries(jsonSchema).forEach(([className, schema]) => {\n if (!schemas[className]) schemas[className] = schema;\n });\n return schemas;\n}\n"]}
|
package/dist/cjs/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AA4CA,wCAOC;AA2HD,kGAIC;AAED,sCAEC;AAEgB,0BAAO;AArLxB,+BAAkC;AAClC,gDAAwB;AACxB,wDAAgC;AAChC,+DAA0D;AAC1D,uGAA4E;AAC5E,yCAAoE;AACpE,+DAAuE;AACvE,6CAAqE;AAErE,wFAAyD;AAEzD,CAAC,eAAe,CAAC,CAAC;AAElB,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAEnC,QAAA,kBAAkB,GAA0C;IACvE,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;IACtE,IAAI,EACF,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,IAAI;QAChB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;IAChE,UAAU,EAAE;QACV,aAAa,EAAE,SAAS;QACxB,SAAS,EAAE,cAAc;KAC1B;IACD,OAAO,EAAE;QACP,MAAM,EAAE,KAAK;KACd;IACD,SAAS,EAAE;QACT,QAAQ,EAAE;YACR,KAAK,EAAE,CAAC;SACT;KACF;CACF,CAAC;AAMF,SAAgB,cAAc;IAC5B,OAAO,IAAA,0BAAS,EACd,0BAAkB,EAClB,OAAO,kBAAkB,KAAK,QAAQ;QACpC,CAAC,CAAC,EAAE;QACJ,CAAC,CAAE,kBAA0B,CAAC,OAAO,CACxC,CAAC;AACJ,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAA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C,IAAI,CAAC,kEAAkE,CACrF,CAAC;QACJ,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,cAAI,CAAC,KAAK,CACR,GAAG,EAAE,OAAO,IAAI,uDAAuD,CACxE,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnB,IAAA,uCAAiC,CAAA,EAAE,EAAE,CAAC;QACtC,IAAA,oCAAsB,CAAA,EAAE,EAAE,CAAC;QAC3B,IAAA,wCAAgC,CAAA,EAAE,EAAE,CAAC;IACvC,CAAC;AACH,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,cAAI,CAAC,KAAK,CAAC,2CAA2C,EAAE;QACtD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,SAAgB,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\nimport { killDevelopmentServerChildProcess } from \"./utils/cli/dev\";\nimport { killServerChildProcess } from \"./utils/cli/utils/cli.helpers\";\nimport { killProductionServerChildProcess } from \"./utils/cli/start\";\nimport { ArkosConfig } from \"./types/new-arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { ArkosInitConfig } from \"./exports\";\n(\"ImportMissing\")
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AA4CA,wCAOC;AA2HD,kGAIC;AAED,sCAEC;AAEgB,0BAAO;AArLxB,+BAAkC;AAClC,gDAAwB;AACxB,wDAAgC;AAChC,+DAA0D;AAC1D,uGAA4E;AAC5E,yCAAoE;AACpE,+DAAuE;AACvE,6CAAqE;AAErE,wFAAyD;AAEzD,CAAC,eAAe,CAAC,CAAC;AAElB,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAEnC,QAAA,kBAAkB,GAA0C;IACvE,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;IACtE,IAAI,EACF,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,IAAI;QAChB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;IAChE,UAAU,EAAE;QACV,aAAa,EAAE,SAAS;QACxB,SAAS,EAAE,cAAc;KAC1B;IACD,OAAO,EAAE;QACP,MAAM,EAAE,KAAK;KACd;IACD,SAAS,EAAE;QACT,QAAQ,EAAE;YACR,KAAK,EAAE,CAAC;SACT;KACF;CACF,CAAC;AAMF,SAAgB,cAAc;IAC5B,OAAO,IAAA,0BAAS,EACd,0BAAkB,E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se } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\nimport { killDevelopmentServerChildProcess } from \"./utils/cli/dev\";\nimport { killServerChildProcess } from \"./utils/cli/utils/cli.helpers\";\nimport { killProductionServerChildProcess } from \"./utils/cli/start\";\nimport { ArkosConfig } from \"./types/new-arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { ArkosInitConfig } from \"./exports\";\n(\"ImportMissing\"); // This will be filled by post build script\n\nconst definedArkosConfig = \"HandledByPostBuild\"; // This will be filled by post build script\n\nexport const defaultArkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host:\n process.env.CLI_HOST ||\n process.env.HOST ||\n (process.env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\"),\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n debugging: {\n requests: {\n level: 1,\n },\n },\n};\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return deepmerge(\n defaultArkosConfig,\n typeof definedArkosConfig === \"string\"\n ? {}\n : (definedArkosConfig as any).default\n );\n}\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosInitConfig} initConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(\n initConfig: ArkosInitConfig = {}\n): Promise<Express | undefined> {\n try {\n const arkosConfig = getArkosConfig();\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n let networkHost = portAndHostAllocator.getFirstNonLocalIp();\n\n _app = await bootstrap(initConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (initConfig?.configureServer) await initConfig.configureServer(server);\n\n server.listen(\n Number(portAndHost?.port),\n portAndHost.host! === \"localhost\" ? \"127.0.0.1\" : portAndHost.host!,\n () => {\n const host = [\"0.0.0.0\", \"127.0.0.1\"].includes(portAndHost?.host)\n ? \"localhost\"\n : portAndHost?.host;\n\n const message = `${sheu.gray(time)} {{server}} waiting on http://${host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (networkHost && portAndHost.host === \"0.0.0.0\")\n sheu.ready(\n message\n .replace(host, networkHost)\n .replace(\"{{server}}\", `Network server`)\n );\n if (\n arkosConfig?.swagger?.mode &&\n ((arkosConfig?.swagger?.enableAfterBuild &&\n process.env.ARKOS_BUILD === \"true\") ||\n process.env.ARKOS_BUILD !== \"true\")\n )\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n }\n );\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n killDevelopmentServerChildProcess?.();\n killServerChildProcess?.();\n killProductionServerChildProcess?.();\n }\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\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/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enable?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/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/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\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?: Partial<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 * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\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 /**\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 expressStatic?: 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 * Defines express middlewares configurations\n */\n middlewares?: {\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 compression?: false | compression.CompressionOptions | ArkosRequestHandler;\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 rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\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} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` 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 | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\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 | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\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 cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\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 parseNumber: 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 queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\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 welcomeRoute?: false | ArkosRequestHandler;\n };\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 * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\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 } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"FinalPrismaQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\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/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/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/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\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?: Partial<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 * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\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 /**\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 expressStatic?: 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 * Defines express middlewares configurations\n */\n middlewares?: {\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 compression?: false | compression.CompressionOptions | ArkosRequestHandler;\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 rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\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} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` 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 | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\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 | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\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 cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\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 parseNumber: 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 queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\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 welcomeRoute?: false | ArkosRequestHandler;\n };\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 * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\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 } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"FinalPrismaQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n};\n"]}
|
|
@@ -57,8 +57,7 @@ function ArkosRouter() {
|
|
|
57
57
|
throw Error("When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.");
|
|
58
58
|
if (!validationConfig?.resolver && config.validation)
|
|
59
59
|
throw Error("Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })");
|
|
60
|
-
if (
|
|
61
|
-
(authenticationConfig && authenticationConfig?.enable !== false))
|
|
60
|
+
if (config.authentication && authenticationConfig?.mode)
|
|
62
61
|
throw Error("Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })");
|
|
63
62
|
handlers = [...(0, helpers_1.getMiddlewareStack)(config), ...handlers];
|
|
64
63
|
return originalMethod.call(target, route, ...handlers);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAmCA,8BA6FC;AAED,wDAyDC;AA3LD,qCAAiC;AAGjC,sFAA4D;AAC5D,oFAA0D;AAC1D,6CAAyE;AACzE,2CAA+C;AAC/C,+DAAyD;AAEzD,4EAAiD;AA0BjD,SAAwB,WAAW;IACjC,MAAM,MAAM,GAAiB,IAAA,gBAAM,GAAE,CAAC;IAEtC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;YAE3D,MAAM,WAAW,GAAG;gBAClB,KAAK;gBACL,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,QAAQ;gBACR,KAAK;gBACL,MAAM;gBACN,OAAO;gBACP,SAAS;aACV,CAAC;YAMF,IAAI,WAAW,CAAC,QAAQ,CAAC,IAAc,CAAC,EAAE,CAAC;gBACzC,OAAO,UACL,MAAwB,EACxB,GAAG,QAAkC;oBAErC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;oBAE3B,IAAI,CAAC,gCAAoB,CAAC,kBAAkB,CAAC,MAAM,CAAC;wBAClD,MAAM,KAAK,CACT,mCAAmC,IAAc,oDAAoD,MAAM,EAAE,CAC9G,CAAC;oBAEJ,MAAM,MAAM,GAAG,IAAc,CAAC;oBAE9B,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;wBACxB,QAAQ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CAAC,MAAM,CAAC,YAAY,CAAC,OAAO;YAC7B,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,gCAAgC,GACpC,WAAW,EAAE,UAAU,EAAE,QAAQ,KAAK,KAAK;YACzC,CAAC,CAAC,4BAAe;YACjB,CAAC,CAAC,4BAAe,CAAC;QAErB,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YAChD,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAa9C,GAAG,OAAO;SACX,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * route: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const route = config.route;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) =>\n typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n )\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (\n (!authenticationConfig?.mode && config.authentication) ||\n (authenticationConfig && authenticationConfig?.enable !== false)\n )\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n const arkosConfig = getArkosConfig();\n\n routes.forEach(async ({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchemaTransformer =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : zodToJsonSchema;\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n // ...(!openapi.requestBody &&\n // config?.validation?.body && {\n // requestBody: {\n // content: {\n // \"application/json\": {\n // schema: validatorToJsonSchemaTransformer(\n // config?.validation?.body as any\n // ),\n // },\n // },\n // },\n // }),\n ...openapi,\n };\n });\n\n return paths;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAmCA,8BA0FC;AAED,wDAyDC;AAxLD,qCAAiC;AAGjC,sFAA4D;AAC5D,oFAA0D;AAC1D,6CAAyE;AACzE,2CAA+C;AAC/C,+DAAyD;AAEzD,4EAAi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AAE,IAAI,IAAI,EAAE;YAa9C,GAAG,OAAO;SACX,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * route: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const route = config.route;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) =>\n typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n )\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (config.authentication && authenticationConfig?.mode)\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n const arkosConfig = getArkosConfig();\n\n routes.forEach(async ({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchemaTransformer =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : zodToJsonSchema;\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n // ...(!openapi.requestBody &&\n // config?.validation?.body && {\n // requestBody: {\n // content: {\n // \"application/json\": {\n // schema: validatorToJsonSchemaTransformer(\n // config?.validation?.body as any\n // ),\n // },\n // },\n // },\n // }),\n ...openapi,\n };\n });\n\n return paths;\n}\n"]}
|
|
@@ -11,9 +11,9 @@ class RouteConfigValidator {
|
|
|
11
11
|
const swaggerMode = arkosConfig?.swagger?.mode;
|
|
12
12
|
if (config.validation) {
|
|
13
13
|
const validators = [
|
|
14
|
-
{ key: "query", schema: config.validation
|
|
15
|
-
{ key: "body", schema: config.validation
|
|
16
|
-
{ key: "params", schema: config.validation
|
|
14
|
+
{ key: "query", schema: config.validation?.query },
|
|
15
|
+
{ key: "body", schema: config.validation?.body },
|
|
16
|
+
{ key: "params", schema: config.validation?.params },
|
|
17
17
|
];
|
|
18
18
|
for (const { key, schema } of validators) {
|
|
19
19
|
if (!schema)
|
|
@@ -40,14 +40,14 @@ class RouteConfigValidator {
|
|
|
40
40
|
"They will be automatically migrated to OpenAPI specification.");
|
|
41
41
|
}
|
|
42
42
|
if (config.validation.params &&
|
|
43
|
-
openapi.parameters?.some((p) => p.in === "
|
|
43
|
+
openapi.parameters?.some((p) => p.in === "params")) {
|
|
44
44
|
throw new Error("Duplicate path parameter validation definitions. " +
|
|
45
45
|
"When using validation.params, do not define path parameters in openapi.parameters. " +
|
|
46
46
|
"They will be automatically migrated to OpenAPI specification.");
|
|
47
47
|
}
|
|
48
48
|
if (config.validation.body && openapi.requestBody) {
|
|
49
49
|
throw new Error("Duplicate request body validation definitions. " +
|
|
50
|
-
"When using validation.body, do not define requestBody in openapi. " +
|
|
50
|
+
"When using validation.body, do not define openapi.requestBody in openapi. " +
|
|
51
51
|
"It will be automatically migrated to OpenAPI specification.");
|
|
52
52
|
}
|
|
53
53
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-config-validator.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/route-config-validator.ts"],"names":[],"mappings":";;AACA,sDAAyD;AACzD,2CAA+C;AAG/C,MAAqB,oBAAoB;IACvC,MAAM,CAAC,kBAAkB,CAAC,GAAQ;QAChC,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,IAAI,GAAG,CAAC;IACnE,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,MAAwB;QACtC,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;QACrC,MAAM,WAAW,GAAG,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;QAE/C,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACtB,MAAM,UAAU,GAAG;gBACjB,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,UAAU,
|
|
1
|
+
{"version":3,"file":"route-config-validator.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/route-config-validator.ts"],"names":[],"mappings":";;AACA,sDAAyD;AACzD,2CAA+C;AAG/C,MAAqB,oBAAoB;IACvC,MAAM,CAAC,kBAAkB,CAAC,GAAQ;QAChC,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,IAAI,GAAG,CAAC;IACnE,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,MAAwB;QACtC,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;QACrC,MAAM,WAAW,GAAG,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;QAE/C,IAAI,MAAM,CAAC,UAAU,EA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AAI,KAAK,CACb,0CAA0C;oBACxC,qFAAqF;oBACrF,+DAA+D,CAClE,CAAC;YACJ,CAAC;YAED,IACE,MAAM,CAAC,UAAU,CAAC,MAAM;gBACxB,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,QAAQ,CAAC,EACvD,CAAC;gBACD,MAAM,IAAI,KAAK,CACb,mDAAmD;oBACjD,qFAAqF;oBACrF,+DAA+D,CAClE,CAAC;YACJ,CAAC;YAED,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;gBAClD,MAAM,IAAI,KAAK,CACb,iDAAiD;oBAC/C,4EAA4E;oBAC5E,6DAA6D,CAChE,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAzED,uCAyEC","sourcesContent":["import { ArkosRouteConfig } from \"./types\";\nimport { isClass, isZodSchema } from \"../dynamic-loader\";\nimport { getArkosConfig } from \"../../exports\";\nimport { OpenAPIV3 } from \"openapi-types\";\n\nexport default class RouteConfigValidator {\n static isArkosRouteConfig(arg: any): arg is ArkosRouteConfig {\n return typeof arg === \"object\" && arg !== null && \"route\" in arg;\n }\n\n static validate(config: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const swaggerMode = arkosConfig?.swagger?.mode;\n\n if (config.validation) {\n const validators = [\n { key: \"query\", schema: config.validation?.query },\n { key: \"body\", schema: config.validation?.body },\n { key: \"params\", schema: config.validation?.params },\n ];\n\n for (const { key, schema } of validators) {\n if (!schema) continue;\n\n const isZod = isZodSchema(schema);\n const isClassValidator = isClass(schema);\n\n if (isZod && swaggerMode !== \"zod\") {\n throw new Error(\n `Zod schema used in validation.${key} but Swagger mode is '${swaggerMode}'. ` +\n `Zod schemas are only supported when swagger.mode is 'zod'.`\n );\n }\n\n if (isClassValidator && swaggerMode !== \"class-validator\") {\n throw new Error(\n `Class validator used in validation.${key} but Swagger mode is '${swaggerMode}'. ` +\n `Class validators are only supported when swagger.mode is 'class-validator'.`\n );\n }\n }\n }\n\n if (config.validation && typeof config.experimental?.openapi === \"object\") {\n const openapi = config.experimental\n .openapi as Partial<OpenAPIV3.OperationObject>;\n\n if (\n config.validation.query &&\n openapi.parameters?.some((p: any) => p.in === \"query\")\n ) {\n throw new Error(\n \"Duplicate query validation definitions. \" +\n \"When using validation.query, do not define query parameters in openapi.parameters. \" +\n \"They will be automatically migrated to OpenAPI specification.\"\n );\n }\n\n if (\n config.validation.params &&\n openapi.parameters?.some((p: any) => p.in === \"params\")\n ) {\n throw new Error(\n \"Duplicate path parameter validation definitions. \" +\n \"When using validation.params, do not define path parameters in openapi.parameters. \" +\n \"They will be automatically migrated to OpenAPI specification.\"\n );\n }\n\n if (config.validation.body && openapi.requestBody) {\n throw new Error(\n \"Duplicate request body validation definitions. \" +\n \"When using validation.body, do not define openapi.requestBody in openapi. \" +\n \"It will be automatically migrated to OpenAPI specification.\"\n );\n }\n }\n }\n}\n"]}
|
|
@@ -23,7 +23,7 @@ function killServerChildProcess() {
|
|
|
23
23
|
(0, start_1.killProductionServerChildProcess)();
|
|
24
24
|
}
|
|
25
25
|
function getVersion() {
|
|
26
|
-
return "1.4.0-canary.
|
|
26
|
+
return "1.4.0-canary.56";
|
|
27
27
|
}
|
|
28
28
|
async function loadArkosConfig() {
|
|
29
29
|
const configPath = path_1.default.resolve(process.cwd(), `arkos.config.${fs_helpers_1.getUserFileExtension}`);
|
package/dist/esm/app.js
CHANGED
|
@@ -140,7 +140,8 @@ export async function bootstrap(initConfig) {
|
|
|
140
140
|
}
|
|
141
141
|
const fileUploadRouter = getFileUploadRouter(arkosConfig);
|
|
142
142
|
knowModulesRouter.use(fileUploadRouter);
|
|
143
|
-
if (arkosConfig.authentication
|
|
143
|
+
if (arkosConfig.authentication &&
|
|
144
|
+
arkosConfig.authentication?.enabled !== false) {
|
|
144
145
|
const authRouter = getAuthRouter(arkosConfig);
|
|
145
146
|
knowModulesRouter.use("/api", authRouter);
|
|
146
147
|
}
|
package/dist/esm/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAW,MAAM,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,eAAe,MAAM,qCAAqC,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C,MAAM,CAAC,MAAM,GAAG,GAAoB,OAAO,EAAE,CAAC;AAC9C,MAAM,iBAAiB,GAAG,MAAM,EAAE,CAAC;AAEnC,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,UAA2B;IAE3B,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IAErC,MAA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AC;IACxD,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAE5C,GAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC3B,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAExD,IACE,WAAW,CAAC,OAAO;QACnB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YACjC,WAAW,CAAC,OAAO,CAAC,gBAAgB,KAAK,IAAI,CAAC;QAEhD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,gBAAgB,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,CAAC;IAE5D,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,IAAI,QAAQ,CAChB,iBAAiB,EACjB,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,EACnB,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,GAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n if (typeof middlewaresConfig?.cors === \"function\") {\n app.use(middlewaresConfig.cors);\n } else {\n app.use(\n cors(\n middlewaresConfig?.cors?.customHandler\n ? middlewaresConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = (middlewaresConfig?.cors as any)\n ?.allowedOrigins;\n\n if (allowed === \"*\") cb(null, true);\n else if (Array.isArray(allowed))\n cb(null, !origin || allowed?.includes?.(origin));\n else if (typeof allowed === \"string\")\n cb(null, !origin || allowed === origin);\n else cb(null, false);\n },\n\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n middlewaresConfig?.cors?.options || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params = Array.isArray(middlewaresConfig?.cookieParser)\n ? middlewaresConfig.cookieParser\n : [];\n app.use(cookieParser(...(params as any))); // FIXME: check types correctly\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (arkosConfig.authentication) {\n const authRouter = getAuthRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.path },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAW,MAAM,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAA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,GAAG,CAAC,IAAI,EAAE,EACnB,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,GAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n if (typeof middlewaresConfig?.cors === \"function\") {\n app.use(middlewaresConfig.cors);\n } else {\n app.use(\n cors(\n middlewaresConfig?.cors?.customHandler\n ? middlewaresConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = (middlewaresConfig?.cors as any)\n ?.allowedOrigins;\n\n if (allowed === \"*\") cb(null, true);\n else if (Array.isArray(allowed))\n cb(null, !origin || allowed?.includes?.(origin));\n else if (typeof allowed === \"string\")\n cb(null, !origin || allowed === origin);\n else cb(null, false);\n },\n\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n middlewaresConfig?.cors?.options || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params = Array.isArray(middlewaresConfig?.cookieParser)\n ? middlewaresConfig.cookieParser\n : [];\n app.use(cookieParser(...(params as any))); // FIXME: check types correctly\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (\n arkosConfig.authentication &&\n arkosConfig.authentication?.enabled !== false\n ) {\n const authRouter = getAuthRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.path },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { getMetadataStorage } from "class-validator";
|
|
2
|
+
import { validationMetadatasToSchemas } from "class-validator-jsonschema";
|
|
3
|
+
import { importModule } from "../../../../utils/helpers/global.helpers.js";
|
|
4
|
+
export default async function classValidatorToJsonSchema(decoratedClass) {
|
|
5
|
+
const { defaultMetadataStorage } = await importModule("class-transformer/cjs/storage.js");
|
|
6
|
+
const jsonSchemas = validationMetadatasToSchemas({
|
|
7
|
+
classValidatorMetadataStorage: getMetadataStorage(),
|
|
8
|
+
classTransformerMetadataStorage: defaultMetadataStorage,
|
|
9
|
+
refPointerPrefix: "#/components/schemas/",
|
|
10
|
+
});
|
|
11
|
+
return jsonSchemas[decoratedClass.name];
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=class-validator-to-json-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"class-validator-to-json-schema.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/class-validator-to-json-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAExE,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,0BAA0B,CACtD,cAA8C;IAE9C,MAAM,EAAE,sBAAsB,EAAE,GAAG,MAAM,YAAY,CACnD,kCAAkC,CACnC,CAAC;IAEF,MAAM,WAAW,GAAG,4BAA4B,CAAC;QAC/C,6BAA6B,EAAE,kBAAkB,EAAE;QACnD,+BAA+B,EAAE,sBAAsB;QACvD,gBAAgB,EAAE,uBAAuB;KAC1C,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import { getMetadataStorage } from \"class-validator\";\nimport { validationMetadatasToSchemas } from \"class-validator-jsonschema\";\nimport { importModule } from \"../../../../utils/helpers/global.helpers\";\n\nexport default async function classValidatorToJsonSchema(\n decoratedClass: new (...args: any[]) => object\n): Promise<any> {\n const { defaultMetadataStorage } = await importModule(\n \"class-transformer/cjs/storage.js\"\n );\n\n const jsonSchemas = validationMetadatasToSchemas({\n classValidatorMetadataStorage: getMetadataStorage(),\n classTransformerMetadataStorage: defaultMetadataStorage,\n refPointerPrefix: \"#/components/schemas/\",\n });\n\n return jsonSchemas[decoratedClass.name];\n}\n"]}
|
|
@@ -25,9 +25,8 @@ export async function generateClassValidatorJsonSchemas() {
|
|
|
25
25
|
if (dtoClass && !ignoredDtoTypes.includes(dtoType.toLowerCase())) {
|
|
26
26
|
try {
|
|
27
27
|
const schemaName = getCorrectJsonSchemaName(dtoType, modelName, "Dto");
|
|
28
|
-
if (schemas[schemaName])
|
|
28
|
+
if (schemas[schemaName])
|
|
29
29
|
throw Error(`Found more then 1 ${dtoClass.name} classes among your .dto.${getUserFileExtension()} files, there is no way to correctly generate json-schemas for swagger documentation.`);
|
|
30
|
-
}
|
|
31
30
|
schemas[schemaName] = jsonSchema[dtoClass.name] || {};
|
|
32
31
|
}
|
|
33
32
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-class-validator-json-schemas.js","sourceRoot":"","sources":["../../../../../../../src/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,6CAA6C,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC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ources":["../../../../../../../src/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,6CAA6C,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,kBAAkB,MAAM,kDAAkD,CAAC;AAClF,OAAO,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AAE/E,MAAM,CAAC,KAAK,UAAU,iCAAiC;IACrD,MAAM,kBAAkB,GAAG;QACzB,GAAG,kBAAkB,CAAC,yBAAyB,EAAE;QACjD,MAAM;KACP,CAAC;IACF,MAAM,OAAO,GAAwB,EAAE,CAAC;IAExC,MAAM,EAAE,sBAAsB,EAAE,GAAG,MAAM,YAAY,CACnD,kCAAkC,CACnC,CAAC;IAEF,MAAM,UAAU,GAAG,4BAA4B,CAAC;QAC9C,6BAA6B,EAAE,kBAAkB,EAAE;QACnD,+BAA+B,EAAE,sBAAsB;QACvD,gBAAgB,EAAE,uBAAuB;KAC1C,CAAC,CAAC;IAEH,kBAAkB,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;QACvC,MAAM,gBAAgB,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;QAExD,IAAI,gBAAgB,EAAE,IAAI,EAAE,CAAC;YAC3B,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,EAAE;gBACpE,MAAM,eAAe,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;gBACnD,IAAI,QAAQ,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC;oBACjE,IAAI,CAAC;wBACH,MAAM,UAAU,GAAG,wBAAwB,CACzC,OAAO,EACP,SAAS,EACT,KAAK,CACN,CAAC;wBAEF,IAAI,OAAO,CAAC,UAAU,CAAC;4BACrB,MAAM,KAAK,CACT,qBAAqB,QAAQ,CAAC,IAAI,4BAA4B,oBAAoB,EAAE,uFAAuF,CAC5K,CAAC;wBAEJ,OAAO,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;oBACxD,CAAC;oBAAC,OAAO,GAAQ,EAAE,CAAC;wBAClB,MAAM,IAAI,KAAK,CACb,iCAAiC,OAAO,IAAI,SAAS,KAAK,GAAG,CAAC,OAAO,EAAE,CACxE,CAAC;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,EAAE;QACzD,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;YAAE,OAAO,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC;IACvD,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { validationMetadatasToSchemas } from \"class-validator-jsonschema\";\nimport { importModule } from \"../../../../../utils/helpers/global.helpers\";\nimport { getMetadataStorage } from \"class-validator\";\nimport { getModuleComponents } from \"../../../../../utils/dynamic-loader\";\nimport { getCorrectJsonSchemaName } from \"../swagger.router.helpers\";\nimport prismaSchemaParser from \"../../../../../utils/prisma/prisma-schema-parser\";\nimport { getUserFileExtension } from \"../../../../../utils/helpers/fs.helpers\";\n\nexport async function generateClassValidatorJsonSchemas() {\n const requiredAppModules = [\n ...prismaSchemaParser.getModelsAsArrayOfStrings(),\n \"auth\",\n ];\n const schemas: Record<string, any> = {};\n\n const { defaultMetadataStorage } = await importModule(\n \"class-transformer/cjs/storage.js\"\n );\n\n const jsonSchema = validationMetadatasToSchemas({\n classValidatorMetadataStorage: getMetadataStorage(),\n classTransformerMetadataStorage: defaultMetadataStorage,\n refPointerPrefix: \"#/components/schemas/\",\n });\n\n requiredAppModules.forEach((modelName) => {\n const moduleComponents = getModuleComponents(modelName);\n\n if (moduleComponents?.dtos) {\n Object.entries(moduleComponents.dtos).forEach(([dtoType, dtoClass]) => {\n const ignoredDtoTypes = [\"createone\", \"updateone\"];\n if (dtoClass && !ignoredDtoTypes.includes(dtoType.toLowerCase())) {\n try {\n const schemaName = getCorrectJsonSchemaName(\n dtoType,\n modelName,\n \"Dto\"\n );\n\n if (schemas[schemaName])\n throw Error(\n `Found more then 1 ${dtoClass.name} classes among your .dto.${getUserFileExtension()} files, there is no way to correctly generate json-schemas for swagger documentation.`\n );\n\n schemas[schemaName] = jsonSchema[dtoClass.name] || {};\n } catch (err: any) {\n throw new Error(\n `Failed to generate schema for ${dtoType} ${modelName}: ${err.message}`\n );\n }\n }\n });\n }\n });\n\n Object.entries(jsonSchema).forEach(([className, schema]) => {\n if (!schemas[className]) schemas[className] = schema;\n });\n return schemas;\n}\n"]}
|
package/dist/esm/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,cAAc,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,oBAAoB,MAAM,0CAA0C,CAAC;AAC5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,g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C;QAC3B,gCAAgC,EAAE,EAAE,CAAC;IACvC,CAAC;AACH,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,IAAI,CAAC,KAAK,CAAC,2CAA2C,EAAE;QACtD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,MAAM,UAAU,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\nimport { killDevelopmentServerChildProcess } from \"./utils/cli/dev\";\nimport { killServerChildProcess } from \"./utils/cli/utils/cli.helpers\";\nimport { killProductionServerChildProcess } from \"./utils/cli/start\";\nimport { ArkosConfig } from \"./types/new-arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { ArkosInitConfig } from \"./exports\";\n(\"ImportMissing\");\n\nconst definedArkosConfig = \"HandledByPostBuild\";\n\nexport const defaultArkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host:\n process.env.CLI_HOST ||\n process.env.HOST ||\n (process.env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\"),\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n debugging: {\n requests: {\n level: 1,\n },\n },\n};\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return deepmerge(\n defaultArkosConfig,\n typeof definedArkosConfig === \"string\"\n ? {}\n : (definedArkosConfig as any).default\n );\n}\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(\n initConfig: ArkosInitConfig = {}\n): Promise<Express | undefined> {\n try {\n const arkosConfig = getArkosConfig();\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n let networkHost = portAndHostAllocator.getFirstNonLocalIp();\n\n _app = await bootstrap(initConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (initConfig?.configureServer) await initConfig.configureServer(server);\n\n server.listen(\n Number(portAndHost?.port),\n portAndHost.host! === \"localhost\" ? \"127.0.0.1\" : portAndHost.host!,\n () => {\n const host = [\"0.0.0.0\", \"127.0.0.1\"].includes(portAndHost?.host)\n ? \"localhost\"\n : portAndHost?.host;\n\n const message = `${sheu.gray(time)} {{server}} waiting on http://${host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (networkHost && portAndHost.host === \"0.0.0.0\")\n sheu.ready(\n message\n .replace(host, networkHost)\n .replace(\"{{server}}\", `Network server`)\n );\n if (\n arkosConfig?.swagger?.mode &&\n ((arkosConfig?.swagger?.enableAfterBuild &&\n process.env.ARKOS_BUILD === \"true\") ||\n process.env.ARKOS_BUILD !== \"true\")\n )\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n }\n );\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n killDevelopmentServerChildProcess?.();\n killServerChildProcess?.();\n killProductionServerChildProcess?.();\n }\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,cAAc,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,oBAAoB,MAAM,0CAA0C,CAAC;AAC5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,gCAAgC,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AAEzD,CAAC,eAAe,CAAC,CAAC;AAElB,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAEhD,MAAM,CAAC,MAAM,kBAAkB,GAA0C;IACvE,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;IACtE,IAAI,EACF,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,IAAI;QAChB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;IAChE,UAAU,EAAE;QACV,aAAa,EAAE,SAAS;QACxB,SAAS,EAAE,cAAc;KAC1B;IACD,OAAO,EAAE;QACP,MAAM,EAAE,KAAK;KACd;IACD,SAAS,EAAE;QACT,QAAQ,EAAE;YACR,KAAK,EAAE,CAAC;SACT;KACF;CACF,CAAC;AAMF,MAAM,UAAU,cAAc;IAC5B,OAAO,SAAS,CACd,k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server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\nimport { killDevelopmentServerChildProcess } from \"./utils/cli/dev\";\nimport { killServerChildProcess } from \"./utils/cli/utils/cli.helpers\";\nimport { killProductionServerChildProcess } from \"./utils/cli/start\";\nimport { ArkosConfig } from \"./types/new-arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { ArkosInitConfig } from \"./exports\";\n(\"ImportMissing\"); // This will be filled by post build script\n\nconst definedArkosConfig = \"HandledByPostBuild\"; // This will be filled by post build script\n\nexport const defaultArkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host:\n process.env.CLI_HOST ||\n process.env.HOST ||\n (process.env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\"),\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n debugging: {\n requests: {\n level: 1,\n },\n },\n};\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return deepmerge(\n defaultArkosConfig,\n typeof definedArkosConfig === \"string\"\n ? {}\n : (definedArkosConfig as any).default\n );\n}\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosInitConfig} initConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(\n initConfig: ArkosInitConfig = {}\n): Promise<Express | undefined> {\n try {\n const arkosConfig = getArkosConfig();\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n let networkHost = portAndHostAllocator.getFirstNonLocalIp();\n\n _app = await bootstrap(initConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (initConfig?.configureServer) await initConfig.configureServer(server);\n\n server.listen(\n Number(portAndHost?.port),\n portAndHost.host! === \"localhost\" ? \"127.0.0.1\" : portAndHost.host!,\n () => {\n const host = [\"0.0.0.0\", \"127.0.0.1\"].includes(portAndHost?.host)\n ? \"localhost\"\n : portAndHost?.host;\n\n const message = `${sheu.gray(time)} {{server}} waiting on http://${host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (networkHost && portAndHost.host === \"0.0.0.0\")\n sheu.ready(\n message\n .replace(host, networkHost)\n .replace(\"{{server}}\", `Network server`)\n );\n if (\n arkosConfig?.swagger?.mode &&\n ((arkosConfig?.swagger?.enableAfterBuild &&\n process.env.ARKOS_BUILD === \"true\") ||\n process.env.ARKOS_BUILD !== \"true\")\n )\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n }\n );\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n killDevelopmentServerChildProcess?.();\n killServerChildProcess?.();\n killProductionServerChildProcess?.();\n }\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\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/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enable?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/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/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\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?: Partial<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 * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\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 /**\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 expressStatic?: 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 * Defines express middlewares configurations\n */\n middlewares?: {\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 compression?: false | compression.CompressionOptions | ArkosRequestHandler;\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 rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\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} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` 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 | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\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 | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\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 cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\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 parseNumber: 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 queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\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 welcomeRoute?: false | ArkosRequestHandler;\n };\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 * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\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 } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"FinalPrismaQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\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/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/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/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\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?: Partial<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 * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\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 /**\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 expressStatic?: 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 * Defines express middlewares configurations\n */\n middlewares?: {\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 compression?: false | compression.CompressionOptions | ArkosRequestHandler;\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 rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\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} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` 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 | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\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 | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\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 cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\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 parseNumber: 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 queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\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 welcomeRoute?: false | ArkosRequestHandler;\n };\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 * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\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 } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"FinalPrismaQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n};\n"]}
|
|
@@ -50,8 +50,7 @@ export default function ArkosRouter() {
|
|
|
50
50
|
throw Error("When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.");
|
|
51
51
|
if (!validationConfig?.resolver && config.validation)
|
|
52
52
|
throw Error("Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })");
|
|
53
|
-
if (
|
|
54
|
-
(authenticationConfig && authenticationConfig?.enable !== false))
|
|
53
|
+
if (config.authentication && authenticationConfig?.mode)
|
|
55
54
|
throw Error("Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })");
|
|
56
55
|
handlers = [...getMiddlewareStack(config), ...handlers];
|
|
57
56
|
return originalMethod.call(target, route, ...handlers);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAGjC,OAAO,oBAAoB,MAAM,0BAA0B,CAAC;AAC5D,OAAO,mBAAmB,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,OAAO,eAAe,MAAM,oBAAoB,CAAC;AA0BjD,MAAM,CAAC,OAAO,UAAU,WAAW;IACjC,MAAM,MAAM,GAAiB,MAAM,EAAE,CAAC;IAEtC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;YAE3D,MAAM,WAAW,GAAG;gBAClB,KAAK;gBACL,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,QAAQ;gBACR,KAAK;gBACL,MAAM;gBACN,OAAO;gBACP,SAAS;aACV,CAAC;YAMF,IAAI,WAAW,CAAC,QAAQ,CAAC,IAAc,CAAC,EAAE,CAAC;gBACzC,OAAO,UACL,MAAwB,EACxB,GAAG,QAAkC;oBAErC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;oBAE3B,IAAI,CAAC,oBAAoB,CAAC,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AE,EAAE;iBACZ;aACF,CAAC;QACJ,CAAC;QAED,MAAM,OAAO,GACX,OAAO,MAAM,EAAE,YAAY,EAAE,OAAO,KAAK,QAAQ;YACjD,MAAM,CAAC,YAAY,CAAC,OAAO,KAAK,IAAI;YAClC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO;YAC7B,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,gCAAgC,GACpC,WAAW,EAAE,UAAU,EAAE,QAAQ,KAAK,KAAK;YACzC,CAAC,CAAC,eAAe;YACjB,CAAC,CAAC,eAAe,CAAC;QAErB,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YAChD,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAa9C,GAAG,OAAO;SACX,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * route: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const route = config.route;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) =>\n typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n )\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (\n (!authenticationConfig?.mode && config.authentication) ||\n (authenticationConfig && authenticationConfig?.enable !== false)\n )\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n const arkosConfig = getArkosConfig();\n\n routes.forEach(async ({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchemaTransformer =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : zodToJsonSchema;\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n // ...(!openapi.requestBody &&\n // config?.validation?.body && {\n // requestBody: {\n // content: {\n // \"application/json\": {\n // schema: validatorToJsonSchemaTransformer(\n // config?.validation?.body as any\n // ),\n // },\n // },\n // },\n // }),\n ...openapi,\n };\n });\n\n return paths;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils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AAC,eAAe,CAAC;QAErB,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YAChD,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAa9C,GAAG,OAAO;SACX,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * route: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const route = config.route;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) =>\n typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n )\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (config.authentication && authenticationConfig?.mode)\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n const arkosConfig = getArkosConfig();\n\n routes.forEach(async ({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchemaTransformer =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : zodToJsonSchema;\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n // ...(!openapi.requestBody &&\n // config?.validation?.body && {\n // requestBody: {\n // content: {\n // \"application/json\": {\n // schema: validatorToJsonSchemaTransformer(\n // config?.validation?.body as any\n // ),\n // },\n // },\n // },\n // }),\n ...openapi,\n };\n });\n\n return paths;\n}\n"]}
|
|
@@ -9,9 +9,9 @@ export default class RouteConfigValidator {
|
|
|
9
9
|
const swaggerMode = arkosConfig?.swagger?.mode;
|
|
10
10
|
if (config.validation) {
|
|
11
11
|
const validators = [
|
|
12
|
-
{ key: "query", schema: config.validation
|
|
13
|
-
{ key: "body", schema: config.validation
|
|
14
|
-
{ key: "params", schema: config.validation
|
|
12
|
+
{ key: "query", schema: config.validation?.query },
|
|
13
|
+
{ key: "body", schema: config.validation?.body },
|
|
14
|
+
{ key: "params", schema: config.validation?.params },
|
|
15
15
|
];
|
|
16
16
|
for (const { key, schema } of validators) {
|
|
17
17
|
if (!schema)
|
|
@@ -38,14 +38,14 @@ export default class RouteConfigValidator {
|
|
|
38
38
|
"They will be automatically migrated to OpenAPI specification.");
|
|
39
39
|
}
|
|
40
40
|
if (config.validation.params &&
|
|
41
|
-
openapi.parameters?.some((p) => p.in === "
|
|
41
|
+
openapi.parameters?.some((p) => p.in === "params")) {
|
|
42
42
|
throw new Error("Duplicate path parameter validation definitions. " +
|
|
43
43
|
"When using validation.params, do not define path parameters in openapi.parameters. " +
|
|
44
44
|
"They will be automatically migrated to OpenAPI specification.");
|
|
45
45
|
}
|
|
46
46
|
if (config.validation.body && openapi.requestBody) {
|
|
47
47
|
throw new Error("Duplicate request body validation definitions. " +
|
|
48
|
-
"When using validation.body, do not define requestBody in openapi. " +
|
|
48
|
+
"When using validation.body, do not define openapi.requestBody in openapi. " +
|
|
49
49
|
"It will be automatically migrated to OpenAPI specification.");
|
|
50
50
|
}
|
|
51
51
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-config-validator.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/route-config-validator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAG/C,MAAM,CAAC,OAAO,OAAO,oBAAoB;IACvC,MAAM,CAAC,kBAAkB,CAAC,GAAQ;QAChC,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,IAAI,GAAG,CAAC;IACnE,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,MAAwB;QACtC,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,WAAW,GAAG,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;QAE/C,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACtB,MAAM,UAAU,GAAG;gBACjB,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,UAAU,
|
|
1
|
+
{"version":3,"file":"route-config-validator.js","sour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AgB,IAAI,WAAW,KAAK,iBAAiB,EAAE,CAAC;oBAC1D,MAAM,IAAI,KAAK,CACb,sCAAsC,GAAG,yBAAyB,WAAW,KAAK;wBAChF,6EAA6E,CAChF,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,MAAM,CAAC,UAAU,IAAI,OAAO,MAAM,CAAC,YAAY,EAAE,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC1E,MAAM,OAAO,GAAG,MAAM,CAAC,YAAY;iBAChC,OAA6C,CAAC;YAEjD,IACE,MAAM,CAAC,UAAU,CAAC,KAAK;gBACvB,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,OAAO,CAAC,EACtD,CAAC;gBACD,MAAM,IAAI,KAAK,CACb,0CAA0C;oBACxC,qFAAqF;oBACrF,+DAA+D,CAClE,CAAC;YACJ,CAAC;YAED,IACE,MAAM,CAAC,UAAU,CAAC,MAAM;gBACxB,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,QAAQ,CAAC,EACvD,CAAC;gBACD,MAAM,IAAI,KAAK,CACb,mDAAmD;oBACjD,qFAAqF;oBACrF,+DAA+D,CAClE,CAAC;YACJ,CAAC;YAED,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;gBAClD,MAAM,IAAI,KAAK,CACb,iDAAiD;oBAC/C,4EAA4E;oBAC5E,6DAA6D,CAChE,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ArkosRouteConfig } from \"./types\";\nimport { isClass, isZodSchema } from \"../dynamic-loader\";\nimport { getArkosConfig } from \"../../exports\";\nimport { OpenAPIV3 } from \"openapi-types\";\n\nexport default class RouteConfigValidator {\n static isArkosRouteConfig(arg: any): arg is ArkosRouteConfig {\n return typeof arg === \"object\" && arg !== null && \"route\" in arg;\n }\n\n static validate(config: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const swaggerMode = arkosConfig?.swagger?.mode;\n\n if (config.validation) {\n const validators = [\n { key: \"query\", schema: config.validation?.query },\n { key: \"body\", schema: config.validation?.body },\n { key: \"params\", schema: config.validation?.params },\n ];\n\n for (const { key, schema } of validators) {\n if (!schema) continue;\n\n const isZod = isZodSchema(schema);\n const isClassValidator = isClass(schema);\n\n if (isZod && swaggerMode !== \"zod\") {\n throw new Error(\n `Zod schema used in validation.${key} but Swagger mode is '${swaggerMode}'. ` +\n `Zod schemas are only supported when swagger.mode is 'zod'.`\n );\n }\n\n if (isClassValidator && swaggerMode !== \"class-validator\") {\n throw new Error(\n `Class validator used in validation.${key} but Swagger mode is '${swaggerMode}'. ` +\n `Class validators are only supported when swagger.mode is 'class-validator'.`\n );\n }\n }\n }\n\n if (config.validation && typeof config.experimental?.openapi === \"object\") {\n const openapi = config.experimental\n .openapi as Partial<OpenAPIV3.OperationObject>;\n\n if (\n config.validation.query &&\n openapi.parameters?.some((p: any) => p.in === \"query\")\n ) {\n throw new Error(\n \"Duplicate query validation definitions. \" +\n \"When using validation.query, do not define query parameters in openapi.parameters. \" +\n \"They will be automatically migrated to OpenAPI specification.\"\n );\n }\n\n if (\n config.validation.params &&\n openapi.parameters?.some((p: any) => p.in === \"params\")\n ) {\n throw new Error(\n \"Duplicate path parameter validation definitions. \" +\n \"When using validation.params, do not define path parameters in openapi.parameters. \" +\n \"They will be automatically migrated to OpenAPI specification.\"\n );\n }\n\n if (config.validation.body && openapi.requestBody) {\n throw new Error(\n \"Duplicate request body validation definitions. \" +\n \"When using validation.body, do not define openapi.requestBody in openapi. \" +\n \"It will be automatically migrated to OpenAPI specification.\"\n );\n }\n }\n }\n}\n"]}
|
|
@@ -14,7 +14,7 @@ export function killServerChildProcess() {
|
|
|
14
14
|
killProductionServerChildProcess();
|
|
15
15
|
}
|
|
16
16
|
export function getVersion() {
|
|
17
|
-
return "1.4.0-canary.
|
|
17
|
+
return "1.4.0-canary.56";
|
|
18
18
|
}
|
|
19
19
|
export async function loadArkosConfig() {
|
|
20
20
|
const configPath = path.resolve(process.cwd(), `arkos.config.${getUserFileExtension}`);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default function classValidatorToJsonSchema(decoratedClass: new (...args: any[]) => object): Promise<any>;
|