arkos 1.5.7-beta → 1.5.9-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/app.js +4 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/auth/auth.router.js +3 -0
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +2 -1
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +3 -0
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +18 -42
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js +0 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +8 -9
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +2 -1
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +1 -1
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +3 -1
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/dotenv.helpers.js +0 -6
- package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/arkos-config.helpers.js +17 -0
- package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +7 -8
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/url-helpers.js +14 -0
- package/dist/cjs/utils/helpers/url-helpers.js.map +1 -0
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +12 -6
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-schema-parser.js +10 -3
- package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/esm/app.js +5 -2
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/modules/auth/auth.router.js +3 -0
- package/dist/esm/modules/auth/auth.router.js.map +1 -1
- package/dist/esm/modules/base/base.middlewares.js +2 -1
- package/dist/esm/modules/base/base.middlewares.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js +3 -0
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +18 -42
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/app-error.js +0 -1
- package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +8 -9
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +2 -1
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/cli/build.js +1 -1
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/dev.js +3 -1
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/dotenv.helpers.js +0 -6
- package/dist/esm/utils/dotenv.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/arkos-config.helpers.js +15 -0
- package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +7 -8
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/url-helpers.js +11 -0
- package/dist/esm/utils/helpers/url-helpers.js.map +1 -0
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +12 -6
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-schema-parser.js +10 -3
- package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/types/modules/error-handler/utils/app-error.d.ts +0 -2
- package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +1 -1
- package/dist/types/types/new-arkos-config.d.ts +23 -0
- package/dist/types/utils/helpers/arkos-config.helpers.d.ts +2 -0
- package/dist/types/utils/helpers/url-helpers.d.ts +1 -0
- package/dist/types/utils/prisma/prisma-schema-parser.d.ts +1 -0
- package/package.json +1 -1
|
@@ -31,8 +31,9 @@ function handleJWTExpired() {
|
|
|
31
31
|
return new app_error_1.default("Your token has expired, Please log again!", 401);
|
|
32
32
|
}
|
|
33
33
|
function handlePrismaClientValidationError(err) {
|
|
34
|
-
const message = err?.message?.split("\n")[err?.message?.split("\n").length - 1]
|
|
35
|
-
|
|
34
|
+
const message = err?.message?.split("\n")[err?.message?.split("\n").length - 1] ||
|
|
35
|
+
"Invalid query arguments";
|
|
36
|
+
return new app_error_1.default(message.split(". Did you")[0], 400, "InvalidQueryArgument");
|
|
36
37
|
}
|
|
37
38
|
function handleAuthenticationError(_) {
|
|
38
39
|
const message = "Authentication failed against the database server. Please check your credentials.";
|
|
@@ -59,15 +60,13 @@ function handleRecordNotFoundError(_) {
|
|
|
59
60
|
return new app_error_1.default(message, 404);
|
|
60
61
|
}
|
|
61
62
|
function handleUniqueConstraintError(err) {
|
|
62
|
-
const field = err?.meta?.target || "unknown
|
|
63
|
-
const message = `Duplicate
|
|
64
|
-
return new app_error_1.default(message, 409,
|
|
65
|
-
`${(0, change_case_helpers_1.pascalCase)(err.meta?.modelName)}${(0, change_case_helpers_1.pascalCase)(err.meta?.target?.[0])}UniqueConstraint`) ||
|
|
66
|
-
"Unknown");
|
|
63
|
+
const field = err?.meta?.target || "unknown";
|
|
64
|
+
const message = `Duplicate unique field(s) ${Array.isArray(field) ? field.map((f) => `'${f}'`).join(", ") : `'${field}'`}`;
|
|
65
|
+
return new app_error_1.default(message, 409, "DuplicateRecords");
|
|
67
66
|
}
|
|
68
67
|
function handleForeignKeyConstraintError(_) {
|
|
69
68
|
const message = "Foreign key constraint violation. Ensure that the referenced record exists.";
|
|
70
|
-
return new app_error_1.default(message, 400);
|
|
69
|
+
return new app_error_1.default(message, 400, "ForeignKeyViolation");
|
|
71
70
|
}
|
|
72
71
|
function handleConstraintFailedError(err) {
|
|
73
72
|
const constraint = err?.meta?.constraint || "unknown constraint";
|
|
@@ -101,7 +100,7 @@ function handleNonExistingRecord(err) {
|
|
|
101
100
|
return new app_error_1.default(message, model ? 400 : 404, `${model ? "Inline" : ""}${(0, change_case_helpers_1.pascalCase)(model || "")}RecordNotFound`);
|
|
102
101
|
}
|
|
103
102
|
function handlePrismaClientInitializationError(_) {
|
|
104
|
-
return new app_error_1.default("Service temporarily unavailable", 503, "ServiceUnavailable");
|
|
103
|
+
return new app_error_1.default("Service temporarily unavailable", 503, "ServiceUnavailable", {});
|
|
105
104
|
}
|
|
106
105
|
function handleRequiredRelationViolationError(err) {
|
|
107
106
|
const modelA = err?.meta?.model_a_name || "Record";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AAaA,wCAEC;AAED,4CAEC;AAED,
|
|
1
|
+
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AAaA,wCAEC;AAED,4CAEC;AAED,8EASC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,0DAiBC;AAED,sFAOC;AAED,oFAUC;AAjJD,oFAGoD;AACpD,4DAAmC;AASnC,SAAgB,cAAc;IAC5B,OAAO,IAAI,mBAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,mBAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAgB,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,GACX,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;QAC/D,yBAAyB,CAAC;IAC5B,OAAO,IAAI,mBAAQ,CACjB,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAC7B,GAAG,EACH,sBAAsB,CACvB,CAAC;AACJ,CAAC;AAED,SAAgB,yBAAyB,CAAC,CAAW;IACnD,MAAM,OAAO,GACX,mFAAmF,CAAC;IACtF,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,6BAA6B,CAAC,CAAW;IACvD,MAAM,OAAO,GACX,qGAAqG,CAAC;IACxG,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,4BAA4B,CAAC,CAAW;IACtD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CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;QACzD,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,IAAI,mBAAQ,CACjB,OAAO,EACP,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EACjB,GAAG,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,IAAA,gCAAU,EAAC,KAAK,IAAI,EAAE,CAAC,gBAAgB,CACnE,CAAC;AACJ,CAAC;AAED,SAAgB,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,mBAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,oBAAoB,EACpB,EAAE,CACH,CAAC;AACJ,CAAC;AAED,SAAgB,oCAAoC,CAAC,GAAa;IAChE,MAAM,MAAM,GAAG,GAAG,EAAE,IAAI,EAAE,YAAY,IAAI,QAAQ,CAAC;IACnD,MAAM,MAAM,GAAG,GAAG,EAAE,IAAI,EAAE,YAAY,IAAI,gBAAgB,CAAC;IAC3D,MAAM,OAAO,GAAG,2DAA2D,IAAA,+BAAS,EAAC,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,QAAQ,IAAA,+BAAS,EAAC,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC;IAEnK,OAAO,IAAI,mBAAQ,CACjB,OAAO,EACP,GAAG,EACH,GAAG,IAAA,gCAAU,EAAC,MAAM,IAAI,EAAE,CAAC,mBAAmB,CAC/C,CAAC;AACJ,CAAC","sourcesContent":["import {\n kebabCase,\n pascalCase,\n} from \"../../../utils/helpers/change-case.helpers\";\nimport AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string;\n message: string;\n meta?: Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message?.split(\"\\n\").length - 1] ||\n \"Invalid query arguments\";\n return new AppError(\n message.split(\". Did you\")[0],\n 400,\n \"InvalidQueryArgument\"\n );\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: any) {\n const field = err?.meta?.target || \"unknown\";\n const message = `Duplicate unique field(s) ${Array.isArray(field) ? field.map((f) => `'${f}'`).join(\", \") : `'${field}'`}`;\n return new AppError(message, 409, \"DuplicateRecords\");\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400, \"ForeignKeyViolation\");\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as some required record was not found`;\n\n const model = err?.meta?.cause\n ? err?.meta?.cause?.split(\"No '\")?.[1]?.split?.(\"'\")?.[0]\n : \"\";\n\n return new AppError(\n message,\n model ? 400 : 404,\n `${model ? \"Inline\" : \"\"}${pascalCase(model || \"\")}RecordNotFound`\n );\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n \"ServiceUnavailable\",\n {}\n );\n}\n\nexport function handleRequiredRelationViolationError(err: AppError) {\n const modelA = err?.meta?.model_a_name || \"Record\";\n const modelB = err?.meta?.model_b_name || \"another record\";\n const message = `This operation violates a required relationship between ${kebabCase(modelA).replaceAll(\"-\", \" \")} and ${kebabCase(modelB).replaceAll(\"-\", \" \")}.`;\n\n return new AppError(\n message,\n 400,\n `${pascalCase(modelA || \"\")}RelationViolation`\n );\n}\n"]}
|
|
@@ -10,7 +10,7 @@ const server_1 = require("../../../../server.js");
|
|
|
10
10
|
class OpenAPIchemaConverter {
|
|
11
11
|
constructor() {
|
|
12
12
|
this.validatorToJsonSchema = (schema) => {
|
|
13
|
-
const validationResolver = (0, server_1.getArkosConfig)()
|
|
13
|
+
const validationResolver = (0, server_1.getArkosConfig)()?.validation?.resolver;
|
|
14
14
|
const fn = validationResolver === "zod"
|
|
15
15
|
? zod_to_json_schema_1.default
|
|
16
16
|
: class_validator_to_json_schema_1.default;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi-schema-converter.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/openapi-schema-converter.ts"],"names":[],"mappings":";;;;;AACA,qEAAwE;AACxE,4EAAiD;AACjD,sGAA0E;AAC1E,+CAAoD;AAOpD,MAAM,qBAAqB;IAGzB;QACE,IAAI,CAAC,qBAAqB,GAAG,CAAC,MAAW,EAAE,EAAE;YAC3C,MAAM,kBAAkB,GAAG,IAAA,uBAAc,GAAE,CAAC,UAAU,EAAE,QAAQ,CAAC;YACjE,MAAM,EAAE,GACN,kBAAkB,KAAK,KAAK;gBAC1B,CAAC,CAAC,4BAAe;gBACjB,CAAC,CAAC,wCAA0B,CAAC;YAEjC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC;QACpB,CAAC,CAAC;IACJ,CAAC;IAQO,YAAY,CAAC,KAAU;QAC7B,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QAEzB,IAAI,IAAA,4BAAW,EAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAEpC,IAAI,IAAA,wBAAO,EAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAEhC,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAEzD,OAAO,KAAK,CAAC;IACf,CAAC;IAQO,aAAa,CAAC,KAAU;QAC9B,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,iBAAiB,CAAC;IACrE,CAAC;IAQO,mBAAmB,CAAC,MAAW;QACrC,IAAI,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,EAAE,IAAI;YAAE,OAAO,MAAM,CAAC;QAE9D,IAAI,IAAA,4BAAW,EAAC,MAAM,CAAC,IAAI,IAAA,wBAAO,EAAC,M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,UAAU,CAAC;QAEzB,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC;YACxB,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC3C,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;YAC1B,CAAC;iBAAM,CAAC;gBACN,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AAED,MAAM,sBAAsB,GAAG,IAAI,qBAAqB,EAAE,CAAC;AAE3D,kBAAe,sBAAsB,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { isClass, isZodSchema } from \"../../../../utils/dynamic-loader\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"./class-validator-to-json-schema\";\nimport { getArkosConfig } from \"../../../../server\";\n\n/**\n * Singleton class responsible for converting various schema formats (Zod, Class DTOs, JSON Schema)\n * into OpenAPI-compliant schema objects. Handles shorthand syntax for responses, request bodies,\n * and parameters.\n */\nclass OpenAPIchemaConverter {\n private validatorToJsonSchema: (schema: any) => any;\n\n constructor() {\n this.validatorToJsonSchema = (schema: any) => {\n const validationResolver = getArkosConfig().validation?.resolver;\n const fn =\n validationResolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n return fn(schema);\n };\n }\n\n /**\n * Checks if a value is a schema-like object (Zod, Class, or JSON Schema).\n *\n * @param value - The value to check\n * @returns True if the value is a schema-like object\n */\n private isSchemaLike(value: any): boolean {\n if (!value) return false;\n\n if (isZodSchema(value)) return true;\n\n if (isClass(value)) return true;\n\n if (this.isPlainObject(value) && value.type) return true;\n\n return false;\n }\n\n /**\n * Checks if a value is a plain JavaScript object.\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\n private isPlainObject(value: any): boolean {\n return Object.prototype.toString.call(value) === \"[object Object]\";\n }\n\n /**\n * Converts a schema-like object (Zod, Class, or JSON Schema) into a JSON Schema object.\n *\n * @param schema - The schema to convert\n * @returns The JSON Schema representation, or undefined if schema is null/undefined\n */\n private convertToJsonSchema(schema: any): any {\n if (this.isPlainObject(schema) && schema?.type) return schema;\n\n if (isZodSchema(schema) || isClass(schema))\n return this.validatorToJsonSchema(schema);\n\n throw new Error(\n `Unsupported schema type. Expected Zod schema, class constructor, or JSON Schema object.`\n );\n }\n\n /**\n * Gets the default description for an HTTP status code.\n *\n * @param statusCode - The HTTP status code\n * @returns A human-readable default description\n */\n private getDefaultDescription(statusCode: string): string {\n const defaults: Record<string, string> = {\n \"200\": \"Success\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"204\": \"No Content\",\n \"400\": \"Bad Request\",\n \"401\": \"Unauthorized\",\n \"403\": \"Forbidden\",\n \"404\": \"Not Found\",\n \"409\": \"Conflict\",\n \"422\": \"Unprocessable Entity\",\n \"500\": \"Internal Server Error\",\n \"502\": \"Bad Gateway\",\n \"503\": \"Service Unavailable\",\n };\n\n return defaults[statusCode] || \"Response\";\n }\n\n /**\n * Core flattening logic that converts a JSON schema into bracket notation.\n * Handles nested objects, arrays, and circular references.\n *\n * @param schema - The JSON schema to flatten\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of flattened field descriptors\n */\n flattenSchemaCore(\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): Array<{ name: string; schema: any; required: boolean }> {\n const flattened: Array<{ name: string; schema: any; required: boolean }> =\n [];\n\n if (schema.$ref) {\n const refPath = schema.$ref;\n if (visitedRefs.has(refPath)) return flattened;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, prefix, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n return flattened;\n }\n\n if (schema.type === \"array\" && schema.items) {\n const arrayPrefix = prefix ? `${prefix}[0]` : \"[0]\";\n\n // Check if items is an array FIRST, before checking for object\n if (schema.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.properties || schema.items.type === \"object\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.type || schema.items.$ref) {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: schema.items.type,\n ...(schema.items.enum && { enum: schema.items.enum }),\n ...(schema.items.format && { format: schema.items.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n if ((schema.type === \"object\" || !schema.type) && schema.properties) {\n for (const [key, value] of Object.entries(schema.properties) as any) {\n const paramName = prefix ? `${prefix}[${key}]` : key;\n\n if (value.$ref) {\n const refPath = value.$ref;\n if (visitedRefs.has(refPath)) continue;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, paramName, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n } else if (value.type === \"array\" && value.items) {\n const arrayPrefix = `${paramName}[0]`;\n if (value.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else if (value.items.type === \"object\" || value.items.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: value.items.type,\n ...(value.items.enum && { enum: value.items.enum }),\n ...(value.items.format && { format: value.items.format }),\n },\n required: false,\n });\n }\n } else if (value.type === \"object\" && value.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value, paramName, visitedRefs)\n );\n } else {\n flattened.push({\n name: paramName,\n schema: {\n type: value.type,\n ...(value.enum && { enum: value.enum }),\n ...(value.format && { format: value.format }),\n },\n required: schema.required?.includes(key) || false,\n });\n }\n }\n return flattened;\n }\n\n // Handle primitive types with prefix\n if (schema.type && prefix) {\n flattened.push({\n name: prefix,\n schema: {\n type: schema.type,\n ...(schema.enum && { enum: schema.enum }),\n ...(schema.format && { format: schema.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n /**\n * Flattens a JSON schema while preserving the schema structure.\n * Converts nested objects and arrays into bracket notation properties.\n * Used for multipart/form-data schema representation.\n *\n * @param schema - The JSON schema to flatten\n * @returns A flattened schema object with bracket notation properties\n */\n flattenSchema(schema: any): any {\n const flattened = this.flattenSchemaCore(schema);\n\n // Convert the flattened array into a schema object\n const flattenedSchema: any = {\n ...schema,\n properties: {},\n required: [],\n };\n\n for (const item of flattened) {\n flattenedSchema.properties[item.name] = item.schema;\n if (item.required) {\n flattenedSchema.required.push(item.name);\n }\n }\n\n // Remove empty required array if no required fields\n if (flattenedSchema.required.length === 0) {\n delete flattenedSchema.required;\n }\n\n return flattenedSchema;\n }\n\n /**\n * Converts a response definition (shorthand, medium, or full format) into a standard\n * OpenAPI ResponseObject.\n *\n * Supports three formats:\n * 1. Shorthand: ProfileDto → assumes application/json + default description\n * 2. Medium: { content: ProfileDto, description: \"...\" } → custom description\n * 3. Full: { content: { \"application/json\": { schema: ProfileDto } } } → full control\n *\n * @param statusCode - The HTTP status code for this response\n * @param definition - The response definition to convert\n * @returns A standard OpenAPI ResponseObject\n */\n convertResponseDefinition(\n statusCode: string,\n definition: any\n ): OpenAPIV3.ResponseObject {\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n description: this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n ...(definition.headers && { headers: definition.headers }),\n ...(definition.links && { links: definition.links }),\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.ResponseObject = {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {},\n };\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n converted.content![mediaType] = {\n ...mediaObj,\n schema: this.convertToJsonSchema(mediaObj.schema),\n };\n }\n\n if (definition.headers) converted.headers = definition.headers;\n if (definition.links) converted.links = definition.links;\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts a request body definition (shorthand, medium, or full format) into a standard\n * OpenAPI RequestBodyObject.\n *\n * Supports three formats:\n * 1. Shorthand: CreateUserDto → assumes application/json + required: true\n * 2. Medium: { content: CreateUserDto, required?: boolean } → custom config\n * 3. Full: { content: { \"application/json\": { schema: CreateUserDto } } } → full control\n *\n * For multipart/form-data, automatically converts the schema into an array of parameters.\n *\n * @param definition - The request body definition to convert\n * @returns A standard OpenAPI RequestBodyObject, or undefined if no definition provided\n */\n convertRequestBodyDefinition(\n definition: any\n ): OpenAPIV3.RequestBodyObject | undefined {\n if (!definition) return undefined;\n\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n required: true,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n required: definition.required === false ? false : true,\n description: definition.description,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.RequestBodyObject = {\n required: definition.required ?? true,\n content: {},\n };\n\n if (definition.description)\n converted.description = definition.description;\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n const jsonSchema = this.convertToJsonSchema(mediaObj.schema);\n\n // For multipart/form-data, flatten the schema into bracket notation\n if (mediaType === \"multipart/form-data\") {\n converted.content[mediaType] = {\n ...mediaObj,\n schema: this.flattenSchema(jsonSchema),\n };\n } else {\n // For other media types (like application/json), keep the full schema\n converted.content[mediaType] = {\n ...mediaObj,\n schema: jsonSchema,\n };\n }\n }\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts an array of parameter definitions, transforming any Zod/Class schemas\n * into JSON Schema objects.\n *\n * @param parameters - Array of parameter definitions to convert\n * @returns Array of standard OpenAPI ParameterObjects, or undefined if no parameters provided\n */\n convertParameters(\n parameters: any[] | undefined\n ): (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined {\n if (!parameters) return undefined;\n\n return parameters.map((param) => {\n if (param.$ref) return param;\n\n if (param.schema)\n return {\n ...param,\n schema: this.convertToJsonSchema(param.schema),\n };\n\n return param;\n });\n }\n\n /**\n * Converts all responses in a responses object, handling shorthand, medium, and full formats.\n *\n * @param responses - Object containing response definitions keyed by status code\n * @returns Object with converted OpenAPI ResponseObjects\n */\n convertResponses(\n responses: Record<string, any> | undefined\n ): Record<string, OpenAPIV3.ResponseObject> | undefined {\n if (!responses) return undefined;\n\n const converted: Record<string, OpenAPIV3.ResponseObject> = {};\n\n for (const [statusCode, definition] of Object.entries(responses)) {\n converted[statusCode] = this.convertResponseDefinition(\n statusCode,\n definition\n );\n }\n\n return converted;\n }\n\n /**\n * Converts a complete OpenAPI operation configuration, processing responses, requestBody,\n * and parameters to handle shorthand syntax and schema conversions.\n *\n * @param config - The OpenAPI operation configuration to convert\n * @returns The converted configuration with all schemas transformed to JSON Schema\n */\n convertOpenAPIConfig(config: any): any {\n if (!config || config === false) return config;\n\n const converted = { ...config };\n\n if (config.responses)\n converted.responses = this.convertResponses(config.responses);\n\n if (config.requestBody)\n converted.requestBody = this.convertRequestBodyDefinition(\n config.requestBody\n );\n\n if (config.parameters)\n converted.parameters = this.convertParameters(config.parameters);\n\n return converted;\n }\n\n /**\n * Converts a JSON schema to OpenAPI parameter objects with flattened paths.\n * This is used for query/path/header parameters.\n *\n * @param paramType - The parameter location (query, path, header, cookie)\n * @param schema - The JSON schema to convert\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of OpenAPI parameter objects\n */\n jsonSchemaToOpenApiParameters(\n paramType: string,\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): any[] {\n const flattened = this.flattenSchemaCore(schema, prefix, visitedRefs);\n\n return flattened.map(({ name, schema, required }) => ({\n in: paramType,\n name,\n required,\n schema,\n }));\n }\n\n resolveRef(rootSchema: any, refPath: string): any {\n if (!refPath.startsWith(\"#/properties/\")) {\n return null;\n }\n\n const path = refPath.substring(2).split(\"/\");\n let current = rootSchema;\n\n for (const part of path) {\n if (current && current[part] !== undefined) {\n current = current[part];\n } else {\n return null;\n }\n }\n\n return current;\n }\n}\n\nconst openApiSchemaConverter = new OpenAPIchemaConverter();\n\nexport default openApiSchemaConverter;\n"]}
|
|
1
|
+
{"version":3,"file":"openapi-schema-converter.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/openapi-schema-converter.ts"],"names":[],"mappings":";;;;;AACA,qEAAwE;AACxE,4EAAiD;AACjD,sGAA0E;AAC1E,+CAAoD;AAOpD,MAAM,qBAAqB;IAGzB;QACE,IAAI,CAAC,qBAAqB,GAAG,CAAC,MAAW,EAAE,EAAE;YAC3C,MAAM,kBAAkB,GAAG,IAAA,uBAAc,GAAE,EAAE,UAAU,EAAE,QAAQ,CAAC;YAClE,MAAM,EAAE,GACN,kBAAkB,KAAK,KAAK;gBAC1B,CAAC,CAAC,4BAAe;gBACjB,CAAC,CAAC,wCAA0B,CAAC;YAEjC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC;QACpB,CAAC,CAAC;IACJ,CAAC;IAQO,YAAY,CAAC,KAAU;QAC7B,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QAEzB,IAAI,IAAA,4BAAW,EAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAEpC,IAAI,IAAA,wBAAO,EAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAEhC,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAEzD,OAAO,KAAK,CA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AE,EAAE,SAAS;YACb,IAAI;YACJ,QAAQ;YACR,MAAM;SACP,CAAC,CAAC,CAAC;IACN,CAAC;IAED,UAAU,CAAC,UAAe,EAAE,OAAe;QACzC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC7C,IAAI,OAAO,GAAG,UAAU,CAAC;QAEzB,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC;YACxB,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC3C,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;YAC1B,CAAC;iBAAM,CAAC;gBACN,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AAED,MAAM,sBAAsB,GAAG,IAAI,qBAAqB,EAAE,CAAC;AAE3D,kBAAe,sBAAsB,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { isClass, isZodSchema } from \"../../../../utils/dynamic-loader\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"./class-validator-to-json-schema\";\nimport { getArkosConfig } from \"../../../../server\";\n\n/**\n * Singleton class responsible for converting various schema formats (Zod, Class DTOs, JSON Schema)\n * into OpenAPI-compliant schema objects. Handles shorthand syntax for responses, request bodies,\n * and parameters.\n */\nclass OpenAPIchemaConverter {\n private validatorToJsonSchema: (schema: any) => any;\n\n constructor() {\n this.validatorToJsonSchema = (schema: any) => {\n const validationResolver = getArkosConfig()?.validation?.resolver;\n const fn =\n validationResolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n return fn(schema);\n };\n }\n\n /**\n * Checks if a value is a schema-like object (Zod, Class, or JSON Schema).\n *\n * @param value - The value to check\n * @returns True if the value is a schema-like object\n */\n private isSchemaLike(value: any): boolean {\n if (!value) return false;\n\n if (isZodSchema(value)) return true;\n\n if (isClass(value)) return true;\n\n if (this.isPlainObject(value) && value.type) return true;\n\n return false;\n }\n\n /**\n * Checks if a value is a plain JavaScript object.\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\n private isPlainObject(value: any): boolean {\n return Object.prototype.toString.call(value) === \"[object Object]\";\n }\n\n /**\n * Converts a schema-like object (Zod, Class, or JSON Schema) into a JSON Schema object.\n *\n * @param schema - The schema to convert\n * @returns The JSON Schema representation, or undefined if schema is null/undefined\n */\n private convertToJsonSchema(schema: any): any {\n if (this.isPlainObject(schema) && schema?.type) return schema;\n\n if (isZodSchema(schema) || isClass(schema))\n return this.validatorToJsonSchema(schema);\n\n throw new Error(\n `Unsupported schema type. Expected Zod schema, class constructor, or JSON Schema object.`\n );\n }\n\n /**\n * Gets the default description for an HTTP status code.\n *\n * @param statusCode - The HTTP status code\n * @returns A human-readable default description\n */\n private getDefaultDescription(statusCode: string): string {\n const defaults: Record<string, string> = {\n \"200\": \"Success\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"204\": \"No Content\",\n \"400\": \"Bad Request\",\n \"401\": \"Unauthorized\",\n \"403\": \"Forbidden\",\n \"404\": \"Not Found\",\n \"409\": \"Conflict\",\n \"422\": \"Unprocessable Entity\",\n \"500\": \"Internal Server Error\",\n \"502\": \"Bad Gateway\",\n \"503\": \"Service Unavailable\",\n };\n\n return defaults[statusCode] || \"Response\";\n }\n\n /**\n * Core flattening logic that converts a JSON schema into bracket notation.\n * Handles nested objects, arrays, and circular references.\n *\n * @param schema - The JSON schema to flatten\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of flattened field descriptors\n */\n flattenSchemaCore(\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): Array<{ name: string; schema: any; required: boolean }> {\n const flattened: Array<{ name: string; schema: any; required: boolean }> =\n [];\n\n if (schema.$ref) {\n const refPath = schema.$ref;\n if (visitedRefs.has(refPath)) return flattened;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, prefix, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n return flattened;\n }\n\n if (schema.type === \"array\" && schema.items) {\n const arrayPrefix = prefix ? `${prefix}[0]` : \"[0]\";\n\n // Check if items is an array FIRST, before checking for object\n if (schema.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.properties || schema.items.type === \"object\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.type || schema.items.$ref) {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: schema.items.type,\n ...(schema.items.enum && { enum: schema.items.enum }),\n ...(schema.items.format && { format: schema.items.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n if ((schema.type === \"object\" || !schema.type) && schema.properties) {\n for (const [key, value] of Object.entries(schema.properties) as any) {\n const paramName = prefix ? `${prefix}[${key}]` : key;\n\n if (value.$ref) {\n const refPath = value.$ref;\n if (visitedRefs.has(refPath)) continue;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, paramName, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n } else if (value.type === \"array\" && value.items) {\n const arrayPrefix = `${paramName}[0]`;\n if (value.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else if (value.items.type === \"object\" || value.items.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: value.items.type,\n ...(value.items.enum && { enum: value.items.enum }),\n ...(value.items.format && { format: value.items.format }),\n },\n required: false,\n });\n }\n } else if (value.type === \"object\" && value.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value, paramName, visitedRefs)\n );\n } else {\n flattened.push({\n name: paramName,\n schema: {\n type: value.type,\n ...(value.enum && { enum: value.enum }),\n ...(value.format && { format: value.format }),\n },\n required: schema.required?.includes(key) || false,\n });\n }\n }\n return flattened;\n }\n\n // Handle primitive types with prefix\n if (schema.type && prefix) {\n flattened.push({\n name: prefix,\n schema: {\n type: schema.type,\n ...(schema.enum && { enum: schema.enum }),\n ...(schema.format && { format: schema.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n /**\n * Flattens a JSON schema while preserving the schema structure.\n * Converts nested objects and arrays into bracket notation properties.\n * Used for multipart/form-data schema representation.\n *\n * @param schema - The JSON schema to flatten\n * @returns A flattened schema object with bracket notation properties\n */\n flattenSchema(schema: any): any {\n const flattened = this.flattenSchemaCore(schema);\n\n // Convert the flattened array into a schema object\n const flattenedSchema: any = {\n ...schema,\n properties: {},\n required: [],\n };\n\n for (const item of flattened) {\n flattenedSchema.properties[item.name] = item.schema;\n if (item.required) {\n flattenedSchema.required.push(item.name);\n }\n }\n\n // Remove empty required array if no required fields\n if (flattenedSchema.required.length === 0) {\n delete flattenedSchema.required;\n }\n\n return flattenedSchema;\n }\n\n /**\n * Converts a response definition (shorthand, medium, or full format) into a standard\n * OpenAPI ResponseObject.\n *\n * Supports three formats:\n * 1. Shorthand: ProfileDto → assumes application/json + default description\n * 2. Medium: { content: ProfileDto, description: \"...\" } → custom description\n * 3. Full: { content: { \"application/json\": { schema: ProfileDto } } } → full control\n *\n * @param statusCode - The HTTP status code for this response\n * @param definition - The response definition to convert\n * @returns A standard OpenAPI ResponseObject\n */\n convertResponseDefinition(\n statusCode: string,\n definition: any\n ): OpenAPIV3.ResponseObject {\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n description: this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n ...(definition.headers && { headers: definition.headers }),\n ...(definition.links && { links: definition.links }),\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.ResponseObject = {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {},\n };\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n converted.content![mediaType] = {\n ...mediaObj,\n schema: this.convertToJsonSchema(mediaObj.schema),\n };\n }\n\n if (definition.headers) converted.headers = definition.headers;\n if (definition.links) converted.links = definition.links;\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts a request body definition (shorthand, medium, or full format) into a standard\n * OpenAPI RequestBodyObject.\n *\n * Supports three formats:\n * 1. Shorthand: CreateUserDto → assumes application/json + required: true\n * 2. Medium: { content: CreateUserDto, required?: boolean } → custom config\n * 3. Full: { content: { \"application/json\": { schema: CreateUserDto } } } → full control\n *\n * For multipart/form-data, automatically converts the schema into an array of parameters.\n *\n * @param definition - The request body definition to convert\n * @returns A standard OpenAPI RequestBodyObject, or undefined if no definition provided\n */\n convertRequestBodyDefinition(\n definition: any\n ): OpenAPIV3.RequestBodyObject | undefined {\n if (!definition) return undefined;\n\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n required: true,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n required: definition.required === false ? false : true,\n description: definition.description,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.RequestBodyObject = {\n required: definition.required ?? true,\n content: {},\n };\n\n if (definition.description)\n converted.description = definition.description;\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n const jsonSchema = this.convertToJsonSchema(mediaObj.schema);\n\n // For multipart/form-data, flatten the schema into bracket notation\n if (mediaType === \"multipart/form-data\") {\n converted.content[mediaType] = {\n ...mediaObj,\n schema: this.flattenSchema(jsonSchema),\n };\n } else {\n // For other media types (like application/json), keep the full schema\n converted.content[mediaType] = {\n ...mediaObj,\n schema: jsonSchema,\n };\n }\n }\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts an array of parameter definitions, transforming any Zod/Class schemas\n * into JSON Schema objects.\n *\n * @param parameters - Array of parameter definitions to convert\n * @returns Array of standard OpenAPI ParameterObjects, or undefined if no parameters provided\n */\n convertParameters(\n parameters: any[] | undefined\n ): (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined {\n if (!parameters) return undefined;\n\n return parameters.map((param) => {\n if (param.$ref) return param;\n\n if (param.schema)\n return {\n ...param,\n schema: this.convertToJsonSchema(param.schema),\n };\n\n return param;\n });\n }\n\n /**\n * Converts all responses in a responses object, handling shorthand, medium, and full formats.\n *\n * @param responses - Object containing response definitions keyed by status code\n * @returns Object with converted OpenAPI ResponseObjects\n */\n convertResponses(\n responses: Record<string, any> | undefined\n ): Record<string, OpenAPIV3.ResponseObject> | undefined {\n if (!responses) return undefined;\n\n const converted: Record<string, OpenAPIV3.ResponseObject> = {};\n\n for (const [statusCode, definition] of Object.entries(responses)) {\n converted[statusCode] = this.convertResponseDefinition(\n statusCode,\n definition\n );\n }\n\n return converted;\n }\n\n /**\n * Converts a complete OpenAPI operation configuration, processing responses, requestBody,\n * and parameters to handle shorthand syntax and schema conversions.\n *\n * @param config - The OpenAPI operation configuration to convert\n * @returns The converted configuration with all schemas transformed to JSON Schema\n */\n convertOpenAPIConfig(config: any): any {\n if (!config || config === false) return config;\n\n const converted = { ...config };\n\n if (config.responses)\n converted.responses = this.convertResponses(config.responses);\n\n if (config.requestBody)\n converted.requestBody = this.convertRequestBodyDefinition(\n config.requestBody\n );\n\n if (config.parameters)\n converted.parameters = this.convertParameters(config.parameters);\n\n return converted;\n }\n\n /**\n * Converts a JSON schema to OpenAPI parameter objects with flattened paths.\n * This is used for query/path/header parameters.\n *\n * @param paramType - The parameter location (query, path, header, cookie)\n * @param schema - The JSON schema to convert\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of OpenAPI parameter objects\n */\n jsonSchemaToOpenApiParameters(\n paramType: string,\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): any[] {\n const flattened = this.flattenSchemaCore(schema, prefix, visitedRefs);\n\n return flattened.map(({ name, schema, required }) => ({\n in: paramType,\n name,\n required,\n schema,\n }));\n }\n\n resolveRef(rootSchema: any, refPath: string): any {\n if (!refPath.startsWith(\"#/properties/\")) {\n return null;\n }\n\n const path = refPath.substring(2).split(\"/\");\n let current = rootSchema;\n\n for (const part of path) {\n if (current && current[part] !== undefined) {\n current = current[part];\n } else {\n return null;\n }\n }\n\n return current;\n }\n}\n\nconst openApiSchemaConverter = new OpenAPIchemaConverter();\n\nexport default openApiSchemaConverter;\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 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 rateLimit?: 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 *@see 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 * forbidNonWhitelisted: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: {\n /**\n * Throws an error for know whitelisted fields\n *\n * @default true\n */\n forbidNonWhitelisted?: boolean;\n };\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/open-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 | \"PrismaFinalQueryArgs\"\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 rateLimit?: 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 *@see 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 * forbidNonWhitelisted: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: {\n /**\n * Throws an error for know whitelisted fields\n *\n * @default true\n */\n forbidNonWhitelisted?: boolean;\n };\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/open-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 | \"PrismaFinalQueryArgs\"\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 * Allows to suppress specific warnings emitted by Arkos at startup or runtime.\n */\n warnings?: {\n /**\n * Suppresses specific warning messages.\n */\n suppress?: {\n /**\n * Suppresses Prisma-related warnings.\n */\n prisma?: {\n /**\n * Suppresses the warning emitted when no Prisma instance is found.\n */\n noInstanceFound?: boolean;\n /**\n * Suppresses the warning emitted when no Prisma schema is found.\n */\n noSchemaFound?: boolean;\n };\n };\n };\n};\n"]}
|
|
@@ -110,12 +110,13 @@ For further help see https://www.arkosjs.com/docs/core-concepts/authentication-s
|
|
|
110
110
|
},
|
|
111
111
|
});
|
|
112
112
|
}
|
|
113
|
+
const hasDuplicatedPath = (path) => /^(\/.+)\1/.test(path);
|
|
113
114
|
function generateOpenAPIFromApp(app) {
|
|
114
115
|
const routes = (0, helpers_1.extractArkosRoutes)(app);
|
|
115
116
|
const arkosConfig = (0, exports_1.getArkosConfig)();
|
|
116
117
|
let paths = {};
|
|
117
118
|
routes.forEach(({ path, method, config }) => {
|
|
118
|
-
if (config?.experimental?.openapi === false)
|
|
119
|
+
if (config?.experimental?.openapi === false || hasDuplicatedPath(path))
|
|
119
120
|
return;
|
|
120
121
|
const originalPath = path;
|
|
121
122
|
const pathParatemersFromRoutePath = (0, helpers_1.extractPathParams)(path);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAkDA,8BAyJC;AAED,wDAyLC;AAtYD,qCAAgD;AAShD,sFAA4D;AAC5D,oFAA0D;AAC1D,6CAKyB;AACzB,2CAA+C;AAC/C,+DAAyD;AACzD,4EAAiD;AACjD,wIAA4G;AAC5G,4HAAkG;AAClG,oFAA2D;AAC3D,sDAA6D;AAC7D,kGAAuE;AA0BvE,SAAwB,WAAW,CACjC,OAEC;IAED,MAAM,MAAM,GAAG,IAAA,gBAAM,EAAC,OAAO,CAAC,CAAC;IAE/B,OAAO,IAAI,KAAK,CAAC,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AG,qBAAqB,CAClC,MAAM,EAAE,UAAU,EAAE,IAAW,CAChC,CAAC;wBAEF,OAAO;4BACL,GAAG,gBAAgB,EAAE,WAAW,EAAE,OAAO;4BACzC,GAAG,CAAC,eAAe,IAAI;gCACrB,qBAAqB,EAAE;oCACrB,MAAM,EAAE,kCAAsB,CAAC,aAAa,CAC1C,sCAAyB,CAAC,eAAe,CACvC,MAAM,CAAC,YAAY,EAAE,OAAQ,EAC7B,MAAM,CACP,CACF;iCACF;6BACF,CAAC;4BACF,kBAAkB,EAAE;gCAClB,MAAM;6BACP;yBACF,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;YACJ,GAAG,CAAC,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;gBAC9D,EAAE,MAAM;gBACR,CAAC,mBAAmB;gBACpB,CAAE,MAAc,EAAE,UAAU,EAAE,IAAI;gBAClC,eAAe,IAAI;gBACjB,WAAW,EAAE;oBACX,OAAO,EAAE,CAAC,GAAG,EAAE;wBACb,MAAM,MAAM,GACV,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;4BAC1D,EAAE,MAAM,CAAC;wBAEb,OAAO;4BACL,qBAAqB,EAAE;gCACrB,MAAM,EAAE,kCAAsB,CAAC,aAAa,CAC1C,sCAAyB,CAAC,eAAe,CACvC,MAAM,EAAE,YAAY,EAAE,OAAQ,IAAI,EAAE,EACpC,MAAM,CACP,CACF;6BACF;4BACD,GAAG,gBAAgB,EAAE,WAAW,EAAE,OAAO;yBAC1C,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;SACL,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router, RouterOptions } from \"express\";\nimport {\n IArkosRouter,\n ArkosRouteConfig,\n ArkosAnyRequestHandler,\n PathParams,\n IArkosRoute,\n} from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport {\n applyPrefix,\n extractArkosRoutes,\n extractPathParams,\n getMiddlewareStack,\n} from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport arkosRouterOpenApiManager from \"./arkos-router-openapi-manager\";\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 * path: \"/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(\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n }\n): IArkosRouter {\n const router = Router(options);\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 ] as const;\n\n if (prop === \"route\") {\n return function (path: PathParams) {\n const routeChain: any = {};\n\n httpMethods.forEach((method) => {\n routeChain[method] = function (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const fullConfig: ArkosRouteConfig = {\n ...config,\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\n\n return routeChain as IArkosRoute;\n };\n });\n\n return routeChain;\n };\n }\n\n if (httpMethods.includes(prop as any)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = { ...config, path };\n\n if ([null, undefined].includes(path as any))\n throw Error(\n \"Please pass valid value for path field to use in your route\"\n );\n\n const method = prop as string;\n const UndefinedHandlerError = (handler: any) =>\n Error(\n `Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`\n );\n\n if (handlers.length > 0) {\n const flattenHandlers = (arr: any[]): ArkosAnyRequestHandler[] => {\n return arr.reduce((flat, item) => {\n return flat.concat(\n Array.isArray(item) ? flattenHandlers(item) : item\n );\n }, []);\n };\n\n const flatHandlers = flattenHandlers(handlers);\n\n handlers = flatHandlers.map((handler: ArkosAnyRequestHandler) => {\n if (!handler) throw UndefinedHandlerError(handler);\n\n if (typeof handler !== \"function\") {\n throw UndefinedHandlerError(handler);\n }\n\n return catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\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 const route = `${method.toUpperCase()} ${path}`;\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 (\n !validationConfig?.resolver &&\n Object.keys(config.validation || {}).length > 0\n )\n throw Error(\n `Trying to pass validators into route ${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 route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication-system.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n let wildcardCount = (path.match(/\\*/g) || []).length;\n let wildcardIndex = 0;\n path = path.replace(/\\*/g, () => {\n wildcardIndex++;\n return wildcardCount === 1 ? \"{path}\" : `{path${wildcardIndex}}`;\n });\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 validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpenApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\" &&\n param.name !== \"*\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n const hasUploadFields =\n Object.keys(config?.experimental?.uploads || {}).length > 0;\n const multipartFormSchema =\n convertedOpenAPI?.requestBody?.content?.[\"multipart/form-data\"];\n\n if (hasUploadFields && multipartFormSchema)\n arkosRouterOpenApiManager.validateMultipartFormDocs(\n multipartFormSchema,\n path,\n config?.experimental?.uploads\n );\n\n (paths as any)[path][method.toLowerCase()] = {\n ...convertedOpenAPI,\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: openapi.operationId || `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: (() => {\n const schema = validatorToJsonSchema(\n config?.validation?.body as any\n );\n\n return {\n ...convertedOpenAPI?.requestBody?.content,\n ...(hasUploadFields && {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config.experimental?.uploads!,\n schema\n )\n ),\n },\n }),\n \"application/json\": {\n schema,\n },\n };\n })(),\n },\n }),\n ...(convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema &&\n !multipartFormSchema &&\n !(config as any)?.validation?.body &&\n hasUploadFields && {\n requestBody: {\n content: (() => {\n const schema =\n convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema;\n\n return {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config?.experimental?.uploads! || {},\n schema\n )\n ),\n },\n ...convertedOpenAPI?.requestBody?.content,\n };\n })(),\n },\n }),\n };\n });\n\n return paths;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAkDA,8BAyJC;AAID,wDA0LC;AAzYD,qCAAgD;AAShD,sFAA4D;AAC5D,oFAA0D;AAC1D,6CAKyB;AACzB,2CAA+C;AAC/C,+DAAyD;AACzD,4EAAiD;AACjD,wIAA4G;AAC5G,4HAAkG;AAClG,oFAA2D;AAC3D,sDAA6D;AAC7D,kGAAuE;AA0BvE,SAAwB,WAAW,CACjC,OAEC;IAED,MAAM,MAAM,GAAG,IAAA,gBAAM,EAAC,OAAO,CAAC,CAAC;IAE/B,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,M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n ArkosAnyRequestHandler,\n PathParams,\n IArkosRoute,\n} from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport {\n applyPrefix,\n extractArkosRoutes,\n extractPathParams,\n getMiddlewareStack,\n} from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport arkosRouterOpenApiManager from \"./arkos-router-openapi-manager\";\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 * path: \"/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(\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n }\n): IArkosRouter {\n const router = Router(options);\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 ] as const;\n\n if (prop === \"route\") {\n return function (path: PathParams) {\n const routeChain: any = {};\n\n httpMethods.forEach((method) => {\n routeChain[method] = function (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const fullConfig: ArkosRouteConfig = {\n ...config,\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\n\n return routeChain as IArkosRoute;\n };\n });\n\n return routeChain;\n };\n }\n\n if (httpMethods.includes(prop as any)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = { ...config, path };\n\n if ([null, undefined].includes(path as any))\n throw Error(\n \"Please pass valid value for path field to use in your route\"\n );\n\n const method = prop as string;\n const UndefinedHandlerError = (handler: any) =>\n Error(\n `Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`\n );\n\n if (handlers.length > 0) {\n const flattenHandlers = (arr: any[]): ArkosAnyRequestHandler[] => {\n return arr.reduce((flat, item) => {\n return flat.concat(\n Array.isArray(item) ? flattenHandlers(item) : item\n );\n }, []);\n };\n\n const flatHandlers = flattenHandlers(handlers);\n\n handlers = flatHandlers.map((handler: ArkosAnyRequestHandler) => {\n if (!handler) throw UndefinedHandlerError(handler);\n\n if (typeof handler !== \"function\") {\n throw UndefinedHandlerError(handler);\n }\n\n return catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\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 const route = `${method.toUpperCase()} ${path}`;\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 (\n !validationConfig?.resolver &&\n Object.keys(config.validation || {}).length > 0\n )\n throw Error(\n `Trying to pass validators into route ${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 route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication-system.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nconst hasDuplicatedPath = (path: string) => /^(\\/.+)\\1/.test(path);\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false || hasDuplicatedPath(path))\n return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n let wildcardCount = (path.match(/\\*/g) || []).length;\n let wildcardIndex = 0;\n path = path.replace(/\\*/g, () => {\n wildcardIndex++;\n return wildcardCount === 1 ? \"{path}\" : `{path${wildcardIndex}}`;\n });\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 validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpenApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\" &&\n param.name !== \"*\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n const hasUploadFields =\n Object.keys(config?.experimental?.uploads || {}).length > 0;\n const multipartFormSchema =\n convertedOpenAPI?.requestBody?.content?.[\"multipart/form-data\"];\n\n if (hasUploadFields && multipartFormSchema)\n arkosRouterOpenApiManager.validateMultipartFormDocs(\n multipartFormSchema,\n path,\n config?.experimental?.uploads\n );\n\n (paths as any)[path][method.toLowerCase()] = {\n ...convertedOpenAPI,\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: openapi.operationId || `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: (() => {\n const schema = validatorToJsonSchema(\n config?.validation?.body as any\n );\n\n return {\n ...convertedOpenAPI?.requestBody?.content,\n ...(hasUploadFields && {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config.experimental?.uploads!,\n schema\n )\n ),\n },\n }),\n \"application/json\": {\n schema,\n },\n };\n })(),\n },\n }),\n ...(convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema &&\n !multipartFormSchema &&\n !(config as any)?.validation?.body &&\n hasUploadFields && {\n requestBody: {\n content: (() => {\n const schema =\n convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema;\n\n return {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config?.experimental?.uploads! || {},\n schema\n )\n ),\n },\n ...convertedOpenAPI?.requestBody?.content,\n };\n })(),\n },\n }),\n };\n });\n\n return paths;\n}\n"]}
|
|
@@ -90,7 +90,7 @@ function buildTypeScriptProject(options, moduleType) {
|
|
|
90
90
|
fs_1.default.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));
|
|
91
91
|
try {
|
|
92
92
|
(0, remove_dir_1.removeDir)(BUILD_DIR);
|
|
93
|
-
(0, child_process_1.execSync)(`
|
|
93
|
+
(0, child_process_1.execSync)(`tsc -p ${tempTsconfigPath}`, {
|
|
94
94
|
stdio: "inherit",
|
|
95
95
|
cwd: process.cwd(),
|
|
96
96
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
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C,UAAU,CAAC,UAAU,CAAC;YAAE,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n // console.info(\"\");\n // console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n // console.info(\n // ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n // .replaceAll(`${process.cwd()}/`, \"\")\n // .replaceAll(\"/\", \"\")}`\n // );\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error: any) {\n console.info(error.stack);\n console.error(\"❌ Error building JavaScript project:\", error.stack);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":";;;;;AAuBA,oCAyCC;AAhED,gDAAwB;AACxB,4CAAoB;AACpB,iDAAyC;AACzC,sDAA6D;AAC7D,sDAA6D;AAC7D,8DAA8E;AAC9E,mDAA2B;AAC3B,kFAAyD;AACzD,8CAA0C;AAC1C,wCAAqC;AAErC,MAAM,SAAS,GAAG,QAAQ,CAAC;AA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AE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;4BAC9B,YAAE,CAAC,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;wBAC/C,CAAC;wBAED,YAAE,CAAC,YAAY,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;oBAC1C,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAGD,gBAAgB,CAAC,SAAS,CAAC,CAAC;QAG5B,MAAM,eAAe,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAE5C,KAAK,MAAM,IAAI,IAAI,eAAe,EAAE,CAAC;YACnC,IAAI,YAAE,CAAC,UAAU,CAAC,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;gBAClD,YAAE,CAAC,YAAY,CACb,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,EAC9B,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAC3B,CAAC;YACJ,CAAC;QACH,CAAC;IAGH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n // console.info(\"\");\n // console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n // console.info(\n // ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n // .replaceAll(`${process.cwd()}/`, \"\")\n // .replaceAll(\"/\", \"\")}`\n // );\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error: any) {\n console.info(error.stack);\n console.error(\"❌ Error building JavaScript project:\", error.stack);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
|