arkos 1.6.2-beta → 1.6.3-canary.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,sBAwFC;AAED,oCAEC;AA1JD,gDAA8C;AAC9C,sDAA8B;AAC9B,kEAAyC;AAEzC,yEAA8E;AAE9E,qCAAyC;AACzC,mEAAkE;AAClE,2DAAiE;AACjE,oGAA0E;AAC1E,+BAA+D;AAC/D,4EAAmD;AACnD,0GAAoG;AACpG,+EAG8C;AACjC,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAE9C,IAAI,SAAgE,CAAC;AACrE,MAAM,QAAQ,GACZ,8EAA8E,CAAC;AACjF,IAAI,YAAY,GAAG,KAAK,CAAC;AAwCzB,SAAgB,KAAK;IACnB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QACpC,MAAM,IAAA,oBAAS,EACb,yDAAyD,IAAA,mCAAY,GAAE,CAAC,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC,4BAA4B,6FAA6F,CACpO,CAAC;IAEJ,IAAI,YAAY;QACd,MAAM,IAAA,oBAAS,EAAC,yCAAyC,QAAQ,EAAE,CAAC,CAAC;IAEvE,MAAM,GAAG,GAAG,IAAA,gDAAqB,EAAC,IAAA,iBAAO,GAAE,EAAE,EAAE,EAAE,KAAK,CAAiB,CAAC;IACxE,IAAA,mBAAQ,EAAC,GAAG,CAAC,CAAC;IACd,YAAY,GAAG,IAAI,CAAC;IAGpB,IAAI,KAAK,GAAa,MAAM,CAAC;IAE7B,KAAK,UAAU,OAAO;QACpB,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAA,iCAAgB,GAAE,EAAE,IAAA,wCAAuB,GAAE,CAAC,CAAC,CAAC;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AAK,KAAK,MAAM,EAAE,CAAC;YACrB,KAAK,GAAG,WAAW,CAAC;YACpB,MAAM,OAAO,EAAE,CAAC;QAClB,CAAC;QAED,IAAA,0CAAmB,GAAE,CAAC;QAEtB,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC;QACtE,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,MAAO,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,SAAS,CAAC;QAElE,IAAK,IAAY,EAAE,MAAM,KAAK,CAAC,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,UAAU;YAC9D,SAAS,GAAG,cAAc,CACxB,IAAI,EACJ,IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;aACC,IAAI,IAAI,CAAC,CAAC,CAAC,YAAY,aAAM,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ;YAC/D,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CACxB,IAAI,EACJ,IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;QAEJ,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IAEF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAgB,YAAY;IAC1B,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import \"./utils/helpers/arkos-config.helpers\"; // just to trigger loading of arkos config\nimport express from \"express\";\nimport setupApp from \"./utils/setup-app\";\nimport { Arkos } from \"./types/arkos\";\nimport initializeApp, { addGlobalErrorHandler } from \"./utils/initialize-app\";\nimport { Express } from \"express\";\nimport { logAppStartup } from \"./server\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport runtimeCliCommander from \"./utils/cli/utils/runtime-cli-commander\";\nimport { IncomingMessage, Server, ServerResponse } from \"http\";\nimport ExitError from \"./utils/helpers/exit-error\";\nimport { applyArkosRouterProxy } from \"./utils/arkos-router/utils/helpers/apply-arkos-router-proxy\";\nimport {\n isProduction,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nexport const app: express.Express = express();\n\nlet appServer: Server<typeof IncomingMessage, typeof ServerResponse>;\nconst docsLink =\n \"https://www.arkosjs.com/docs/core-concepts/routing/setup#setting-up-your-app\";\nlet instanciated = false;\n\n/**\n * Creates and configures an Arkos application instance.\n *\n * Arkos extends Express with a small set of methods for registering routers,\n * loading route/service hooks, and booting the application. All Arkos-specific\n * setup (`app.build()`) must happen before the app starts\n * accepting requests.\n *\n * @example\n * ```ts\n * // Simple setup\n * import arkos from \"arkos\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * app.listen();\n * ```\n *\n * @example\n * ```ts\n * // Custom HTTP server (e.g. for WebSockets)\n * import arkos from \"arkos\";\n * import http from \"http\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * await app.build();\n *\n * const server = http.createServer(app);\n * app.listen(server)\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport function arkos(): Arkos {\n if (process.env.__ARKOS_CLI !== \"true\")\n throw ExitError(\n `Arkos.js application must be started the built-in cli ${isProduction() ? \"'arkos start' in production\" : `'arkos dev' in development`} see https://www.arkosjs.com/docs/getting-started/installation#7-set-up-packagejson-scripts`\n );\n\n if (instanciated)\n throw ExitError(`arkos() must be called only once, see ${docsLink}`);\n\n const app = applyArkosRouterProxy(express(), {}, \"app\") as any as Arkos;\n setupApp(app);\n instanciated = true;\n\n type AppState = \"idle\" | \"building\" | \"built\" | \"listening\";\n let state: AppState = \"idle\";\n\n async function loadApp() {\n await Promise.all([loadPrismaModule(), loadAllModuleComponents()]);\n let _app = initializeApp(app);\n _app = addGlobalErrorHandler(_app);\n\n if (process.env.CLI_COMMAND) await runtimeCliCommander.handle();\n return _app;\n }\n\n app.build = async function () {\n if (state === \"built\" || state === \"building\")\n throw ExitError(`app.build() must only be called once, see ${docsLink}`);\n if (state === \"listening\")\n throw ExitError(\n `app.build() must be called before app.listen(), see ${docsLink}`\n );\n\n state = \"building\";\n const _app = await loadApp();\n state = \"built\";\n return _app;\n };\n\n const originalListen = app.listen.bind(app) as any as Express[\"listen\"];\n type UserCallback = (err?: Error) => void;\n\n const defaultCb = (\n port: number | string,\n host: string,\n cb?: UserCallback\n ) => {\n logAppStartup(port, host);\n return cb || function () {};\n };\n\n app.listen = async function (...args): Promise<Server> {\n process.env.__ARKOS_SERVER_LISTENER = \"arkos\";\n\n if (state === \"listening\")\n throw ExitError(`app.listen() must only be called once, see ${docsLink}`);\n if (state === \"building\")\n throw ExitError(\n `app.build() must be awaited before calling app.listen(), see ${docsLink}`\n );\n\n if (state === \"idle\") {\n state = \"listening\";\n await loadApp();\n }\n\n validateArkosConfig();\n\n const port = Number(process.env.__PORT || process.env.PORT || \"8000\");\n const host = process.env.__HOST! || process.env.HOST || \"0.0.0.0\";\n\n if ((args as any)?.length === 0 || typeof args[0] === \"function\")\n appServer = originalListen(\n port,\n host,\n defaultCb(port, host, args[0] as UserCallback)\n );\n else if (args[0] instanceof Server || typeof args[0] === \"object\")\n appServer = args[0].listen(\n port,\n host,\n defaultCb(port, host, args[1] as UserCallback)\n );\n\n return appServer;\n };\n\n return app;\n}\n\nexport function getAppServer() {\n return appServer;\n}\n"]}
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,sBAwFC;AAED,oCAEC;AA1JD,gDAA8C;AAC9C,sDAA8B;AAC9B,kEAAyC;AAEzC,yEAA8E;AAE9E,qCAAyC;AACzC,mEAAk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AI,SAAS,CAAC;QAElE,IAAK,IAAY,EAAE,MAAM,KAAK,CAAC,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,UAAU;YAC9D,SAAS,GAAG,cAAc,CACxB,IAAI,EACJ,IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;aACC,IAAI,IAAI,CAAC,CAAC,CAAC,YAAY,aAAM,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ;YAC/D,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CACxB,IAAI,EACJ,IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;QAEJ,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IAEF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAgB,YAAY;IAC1B,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import \"./utils/helpers/arkos-config.helpers\"; // just to trigger loading of arkos config\nimport express from \"express\";\nimport setupApp from \"./utils/setup-app\";\nimport { Arkos } from \"./types/arkos\";\nimport initializeApp, { addGlobalErrorHandler } from \"./utils/initialize-app\";\nimport { Express } from \"express\";\nimport { logAppStartup } from \"./server\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport runtimeCliCommander from \"./utils/cli/utils/runtime-cli-commander\";\nimport { IncomingMessage, Server, ServerResponse } from \"http\";\nimport ExitError from \"./utils/helpers/exit-error\";\nimport { applyArkosRouterProxy } from \"./utils/arkos-router/utils/helpers/apply-arkos-router-proxy\";\nimport {\n isProduction,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nexport const app: express.Express = express();\n\nlet appServer: Server<typeof IncomingMessage, typeof ServerResponse>;\nconst docsLink =\n \"https://www.arkosjs.com/docs/core-concepts/routing/setup#setting-up-your-app\";\nlet instanciated = false;\n\n/**\n * Creates and configures an Arkos application instance.\n *\n * Arkos extends Express with a small set of methods for registering routers,\n * loading route/service hooks, and booting the application. All Arkos-specific\n * setup (`app.build()`) must happen before the app starts\n * accepting requests.\n *\n * @example\n * ```ts\n * // Simple setup\n * import arkos from \"arkos\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * app.listen();\n * ```\n *\n * @example\n * ```ts\n * // Custom HTTP server (e.g. for WebSockets)\n * import arkos from \"arkos\";\n * import http from \"http\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * await app.build();\n *\n * const server = http.createServer(app);\n * app.listen(server)\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport function arkos(): Arkos {\n if (process.env.__ARKOS_CLI !== \"true\")\n throw ExitError(\n `Arkos.js application must be started the built-in cli ${isProduction() ? \"'arkos start' in production\" : `'arkos dev' in development`} see https://www.arkosjs.com/docs/getting-started/installation#7-set-up-packagejson-scripts`\n );\n\n if (instanciated)\n throw ExitError(`arkos() must be called only once, see ${docsLink}`);\n\n const app = applyArkosRouterProxy(express(), {}, \"app\") as any as Arkos;\n setupApp(app);\n instanciated = true;\n\n type AppState = \"idle\" | \"building\" | \"built\" | \"listening\";\n let state: AppState = \"idle\";\n\n async function loadApp() {\n await Promise.all([loadPrismaModule(), loadAllModuleComponents()]);\n let _app = initializeApp(app);\n _app = addGlobalErrorHandler(_app);\n\n if (process.env.CLI_COMMAND) await runtimeCliCommander.handle();\n return _app;\n }\n\n app.build = async function () {\n if (state === \"built\" || state === \"building\")\n throw ExitError(`app.build() must only be called once, see ${docsLink}`);\n if (state === \"listening\")\n throw ExitError(\n `app.build() must be called before app.listen(), see ${docsLink}`\n );\n\n state = \"building\";\n const _app = await loadApp();\n state = \"built\";\n return _app;\n };\n\n const originalListen = app.listen.bind(app) as any as Express[\"listen\"];\n type UserCallback = (err?: Error) => void;\n\n const defaultCb = (\n port: number | string,\n host: string,\n cb?: UserCallback\n ) => {\n logAppStartup(port, host);\n return cb || function () {};\n };\n\n app.listen = async function (...args: any[]): Promise<Server> {\n process.env.__ARKOS_SERVER_LISTENER = \"arkos\";\n\n if (state === \"listening\")\n throw ExitError(`app.listen() must only be called once, see ${docsLink}`);\n if (state === \"building\")\n throw ExitError(\n `app.build() must be awaited before calling app.listen(), see ${docsLink}`\n );\n\n if (state === \"idle\") {\n state = \"listening\";\n await loadApp();\n }\n\n validateArkosConfig();\n\n const port = Number(process.env.__PORT || process.env.PORT || \"8000\");\n const host = process.env.__HOST! || process.env.HOST || \"0.0.0.0\";\n\n if ((args as any)?.length === 0 || typeof args[0] === \"function\")\n appServer = originalListen(\n port,\n host,\n defaultCb(port, host, args[0] as UserCallback)\n );\n else if (args[0] instanceof Server || typeof args[0] === \"object\")\n appServer = args[0].listen(\n port,\n host,\n defaultCb(port, host, args[1] as UserCallback)\n );\n\n return appServer;\n };\n\n return app;\n}\n\nexport function getAppServer() {\n return appServer;\n}\n"]}
@@ -12,6 +12,10 @@ const catch_async_1 = __importDefault(require("../error-handler/utils/catch-asyn
12
12
  const server_1 = require("../../server.js");
13
13
  const file_upload_helpers_1 = require("./utils/helpers/file-upload.helpers.js");
14
14
  const dynamic_loader_1 = require("../../utils/dynamic-loader.js");
15
+ function matchesUploadUrl(originalUrl, baseUploadRoute, fileType, fileName) {
16
+ const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;
17
+ return originalUrl === expectedPath || originalUrl.startsWith(expectedPath);
18
+ }
15
19
  class FileUploadController {
16
20
  constructor() {
17
21
  this.uploadFile = (0, catch_async_1.default)(async (req, res, next) => {
@@ -112,10 +116,11 @@ class FileUploadController {
112
116
  default:
113
117
  return next(new app_error_1.default("Invalid file type", 400, "InvalidFileType"));
114
118
  }
119
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
115
120
  try {
116
121
  const { fileUpload } = (0, server_1.getArkosConfig)();
117
122
  const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
118
- const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
123
+ const urlPattern = new RegExp(`${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`);
119
124
  const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
120
125
  if (isExpectedUrlPattern) {
121
126
  const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
@@ -177,9 +182,7 @@ class FileUploadController {
177
182
  return next(new app_error_1.default("No new file uploaded", 400, "MissingNewFile"));
178
183
  if (fileName && fileName.trim() !== "") {
179
184
  try {
180
- const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
181
- const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
182
- const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
185
+ const isExpectedUrlPattern = matchesUploadUrl(req.originalUrl, fileUpload?.baseRoute || "/api/uploads", fileType, fileName);
183
186
  if (isExpectedUrlPattern) {
184
187
  const oldFileUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
185
188
  await uploader.deleteFileByUrl(oldFileUrl);
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAKjE,MAAa,oBAAoB;IAAjC;QAeE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,IAAA,oCAAmB,EAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG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,cAAc,GAAG,GAAG,CAAC;oBAClC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAhYD,oDAgYC;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
1
+ {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAEjE,SAAS,gBAAgB,CACvB,WAAmB,EACnB,eAAuB,EACvB,QAAgB,EAChB,QAAgB;IAEhB,MAAM,YAAY,GAAG,GAAG,eAAe,IAAI,QAAQ,IAAI,QAAQ,EAAE,CAAC;IAClE,OAAO,WAAW,KAAK,YAAY,IAAI,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;AAC9E,CAAC;AAKD,MAAa,oBAAoB;IAAjC;QAeE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,IAAA,oCAAmB,EAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,IAAA,2CAAqB,GAAE,CAAC;YAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;YACxC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M,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\nfunction matchesUploadUrl(\n originalUrl: string,\n baseUploadRoute: string,\n fileType: string,\n fileName: string\n): boolean {\n const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;\n return originalUrl === expectedPath || originalUrl.startsWith(expectedPath);\n}\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n // top of file or a shared utils import\n const escapeRegExp = (value: string) =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n try {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const isExpectedUrlPattern = matchesUploadUrl(\n req.originalUrl,\n fileUpload?.baseRoute || \"/api/uploads\",\n fileType,\n fileName\n );\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA8JA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n // /**\n // * Request signals used to control Arkos's built-in request handling pipeline.\n // *\n // * @since v1.6.0-beta\n // */\n // signals?: {\n // /**\n // * When set to `true` in a `before` hook, Arkos skips its built-in logic for the current pipeline step (e.g. CRUD, authentication, authorization).\n // * Automatically reset to `false` after the step completes.\n // *\n // * @example\n // * ```ts\n // * before: (req, res, next) => {\n // * req.user = myCustomAuth(req);\n // * req.signals.skip = true;\n // * next();\n // * }\n // * ```\n // */\n // skip?: boolean;\n // };\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `multer.single()`\n */\n file?: Express.Multer.File;\n /**\n * Uploaded files, populated when using `multer.array()` or `multer.fields()`.\n *\n */\n files?: Express.Multer.File[] | Record<string, Express.Multer.File[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA8JA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n // /**\n // * Request signals used to control Arkos's built-in request handling pipeline.\n // *\n // * @since v1.6.0-beta\n // */\n // signals?: {\n // /**\n // * When set to `true` in a `before` hook, Arkos skips its built-in logic for the current pipeline step (e.g. CRUD, authentication, authorization).\n // * Automatically reset to `false` after the step completes.\n // *\n // * @example\n // * ```ts\n // * before: (req, res, next) => {\n // * req.user = myCustomAuth(req);\n // * req.signals.skip = true;\n // * next();\n // * }\n // * ```\n // */\n // skip?: boolean;\n // };\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `multer.single()`\n */\n file?: Express.Multer.File;\n /**\n * Uploaded files, populated when using `multer.array()` or `multer.fields()`.\n *\n */\n files?: Express.Multer.File[] | Record<string, Express.Multer.File[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosAnyRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> =\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | Array<\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n >;\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=validator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validator.js","sourceRoot":"","sources":["../../../../src/types/validation/validator.ts"],"names":[],"mappings":"","sourcesContent":["import { ZodSchema } from \"zod\";\n\nexport type Validator =\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import {\n IRoute,\n IRouter,\n IRouterHandler,\n IRouterMatcher,\n Locals,\n} from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { ArkosRouterOptions } from \"..\";\n\nexport type ArkosUseConfig = Pick<\n ArkosRouteConfig,\n | \"authentication\"\n | \"rateLimit\"\n | \"compression\"\n | \"queryParser\"\n | \"bodyParser\"\n | \"disabled\"\n> & {\n path?: PathParams; // optional unlike ArkosRouteConfig where path is required\n};\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type InternalIArkosRouter = IArkosRouter & {\n _arkos: {\n options?: ArkosRouterOptions;\n routes: Array<{\n handler: ArkosAnyRequestHandler;\n config: ArkosRouteConfig;\n method: string;\n }>;\n };\n};\n\nexport type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>;\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n };\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\n/**\n * Handler function for `use` that accepts route configuration and middleware handlers.\n *\n * @param {ArkosUseConfig} config - The use configuration object or path.\n * @param {...ArkosAnyRequestHandler} handlers - Middleware handlers.\n * @returns {T} The router instance.\n */\n\nexport type UseMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (\n config: ArkosUseConfig,\n ...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n ArkosErrorRequestHandler | Array<ArkosErrorRequestHandler>\n >\n ): T;\n (...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>): T;\n };\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\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 interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n use: UseMethodHandler<this>;\n\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | null\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | null\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | null\n | undefined = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\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?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import {\n IRoute,\n IRouter,\n IRouterHandler,\n IRouterMatcher,\n Locals,\n} from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport {\n ArkosAnyRequestHandler,\n ArkosErrorRequestHandler,\n ArkosRequestHandler,\n} from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { ArkosRouterOptions } from \"..\";\nimport { Validator } from \"../../../types/validation/validator\";\n\nexport type ArkosUseConfig = Pick<\n ArkosRouteConfig,\n | \"authentication\"\n | \"rateLimit\"\n | \"compression\"\n | \"queryParser\"\n | \"bodyParser\"\n | \"disabled\"\n> & {\n path?: PathParams; // optional unlike ArkosRouteConfig where path is required\n};\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type InternalIArkosRouter = IArkosRouter & {\n _arkos: {\n options?: ArkosRouterOptions;\n routes: Array<{\n handler: ArkosAnyRequestHandler;\n config: ArkosRouteConfig;\n method: string;\n }>;\n };\n};\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n // (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n };\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\n/**\n * Handler function for `use` that accepts route configuration and middleware handlers.\n *\n * @param {ArkosUseConfig} config - The use configuration object or path.\n * @param {...ArkosAnyRequestHandler} handlers - Middleware handlers.\n * @returns {T} The router instance.\n */\n\nexport type UseMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (\n config: ArkosUseConfig,\n ...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n ArkosErrorRequestHandler | Array<ArkosErrorRequestHandler>\n >\n ): T;\n (...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>): T;\n };\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\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 interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n use: UseMethodHandler<this>;\n\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\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?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"apply-arkos-router-proxy.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.ts"],"names":[],"mappings":";;;;;AAmBA,sDAoOC;AA9OD,0FAAgE;AAChE,wBAAoD;AACpD,4DAAmE;AACnE,+CAAoD;AACpD,wFAA8D;AAC9D,qEAA+D;AAC/D,yFAA0D;AAC1D,6EAAoD;AACpD,sEAA6C;AAE7C,SAAgB,qBAAqB,CACnC,MAAS,EACT,OAGC,EACD,YAA8B,QAAQ;IAErC,MAA+B,CAAC,MAAM,GAAG;QACxC,OAAO;QACP,MAAM,EAAE,EAAE;KACX,CAAC;IAEF,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAa,CAAC;YAEvE,MAAM,WAAW,GAAG;gBAClB,KAAK;gBACL,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,QAAQ;gBACR,KAAK;gBACL,MAAM;gBACN,OAAO;gBACP,SAAS;aACD,CAAC;YAEX,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;gBACnB,OAAO,UACL,MAA4D,EAC5D,GAAG,QAAkC;oBAGrC,IAAI,OAAO,MAAM,KAAK,UAAU,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;wBAC1D,QAAQ,GAAG,CAAC,MAAgC,EAAE,GAAG,QAAQ,CAAC,CAAC;wBAC3D,MAAM,G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AAU,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;wBAE/C,MAAM,IAAA,oBAAS,EACb,wCAAwC,KAAK,qHAAqH,CACnK,CAAC;oBAEJ,IAAI,MAAM,CAAC,cAAc,IAAI,CAAC,oBAAoB,EAAE,IAAI;wBACtD,MAAM,IAAA,oBAAS,EACb,gCAAgC,KAAK,+DAA+D,IAAA,iCAAoB,GAAE;;sFAElD,CACzE,CAAC;oBAEJ,QAAQ,GAAG,CAAC,GAAG,IAAA,qBAAkB,EAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAExD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;wBACvB,MAAM,IAAA,oBAAS,EACb,kCAAkC,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,GAAG,CAClE,CAAC;oBAEJ,IACE,MAAM,CAAC,YAAY,EAAE,OAAO;wBAC5B,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,KAAK,KAAK;wBAEnD,QAAQ,CAAC,IAAI,CACX,IAAA,0BAAU,EACR,wBAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,EAC5D,EAAE,IAAI,EAAE,OAAO,EAAE,CAClB,CACF,CAAC;oBAEJ,OAAO,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBACxD,CAAC,CAAC;YACJ,CAAC;YAED,OAAO,cAAc,CAAC;QACxB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { RouterOptions } from \"express\";\nimport {\n ArkosAnyRequestHandler,\n ArkosRouteConfig,\n ArkosUseConfig,\n IArkosRoute,\n InternalIArkosRouter,\n PathParams,\n} from \"../../types\";\nimport RouteConfigValidator from \"../../route-config-validator\";\nimport { applyPrefix, getMiddlewareStack } from \".\";\nimport { getUserFileExtension } from \"../../../helpers/fs.helpers\";\nimport { getArkosConfig } from \"../../../../server\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\nimport deepmerge from \"../../../helpers/deepmerge.helper\";\nimport ExitError from \"../../../helpers/exit-error\";\nimport uploadManager from \"./upload-manager\";\n\nexport function applyArkosRouterProxy<T extends object>(\n target: T,\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n openapi?: { tags?: string[] };\n },\n component: \"app\" | \"router\" = \"router\"\n): T {\n (target as InternalIArkosRouter)._arkos = {\n options,\n routes: [],\n };\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver) as Function;\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 === \"use\") {\n return function (\n config: ArkosUseConfig | PathParams | ArkosAnyRequestHandler,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n // normalize function/router to ArkosUseConfig\n if (typeof config === \"function\" || Array.isArray(config)) {\n handlers = [config as ArkosAnyRequestHandler, ...handlers];\n config = {} as ArkosUseConfig;\n } else if (\n !config ||\n typeof config !== \"object\" ||\n typeof config === \"string\" ||\n config instanceof RegExp\n ) {\n throw ExitError(\n `First argument of ${component}.use() must be a valid ArkosRouteConfig object or a middleware function, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}.`\n );\n }\n\n if ((config as ArkosUseConfig).disabled) return;\n\n const useConfig = config as ArkosUseConfig;\n const path = applyPrefix(options?.prefix, useConfig.path ?? \"/\");\n\n const arkosConfig = getArkosConfig();\n const authenticationConfig = arkosConfig.authentication;\n\n if (useConfig.authentication && !authenticationConfig?.mode)\n throw ExitError(\n `Trying to authenticate route use${path ? ` ${path}` : \"\"} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n const middlewareStack = getMiddlewareStack(useConfig);\n const allHandlers = [...middlewareStack, ...handlers];\n\n return originalMethod.call(target, path, ...allHandlers);\n };\n }\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 if (typeof config === \"function\" || Array.isArray(config))\n throw ExitError(\n `First argument of ${component}.route(\"${path}\").${method}() must be a valid ArkosRouteConfig object without path field, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const fullConfig: ArkosRouteConfig = {\n ...config,\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\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 || !RouteConfigValidator.isArkosRouteConfig(config))\n throw ExitError(\n `First argument of ${component}.${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 if (config?.disabled) return;\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = {\n ...config,\n ...(options?.openapi\n ? {\n experimental: {\n ...config?.experimental,\n openapi: deepmerge(\n options.openapi || {},\n config?.experimental?.openapi || {}\n ),\n },\n }\n : {}),\n path,\n };\n\n if ([null, undefined].includes(path as any))\n throw new 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 ExitError(\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 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 (target as InternalIArkosRouter)._arkos.routes.push({\n handler: finalHandler,\n config,\n method,\n });\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 ExitError(\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 ExitError(\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 ExitError(\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/setup.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (handlers.length === 0)\n throw ExitError(\n `No handlers provided for route ${method.toUpperCase()} ${path}.`\n );\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 });\n}\n"]}
1
+ {"version":3,"file":"apply-arkos-router-proxy.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/help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,IAAA,qBAAkB,EAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAExD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;wBACvB,MAAM,IAAA,oBAAS,EACb,kCAAkC,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,GAAG,CAClE,CAAC;oBAEJ,IACE,MAAM,CAAC,YAAY,EAAE,OAAO;wBAC5B,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,KAAK,KAAK;wBAEnD,QAAQ,CAAC,IAAI,CACX,IAAA,0BAAU,EACR,wBAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,EAC5D,EAAE,IAAI,EAAE,OAAO,EAAE,CAClB,CACF,CAAC;oBAEJ,OAAO,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBACxD,CAAC,CAAC;YACJ,CAAC;YAED,OAAO,cAAc,CAAC;QACxB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { RouterOptions } from \"express\";\nimport {\n ArkosRouteConfig,\n ArkosUseConfig,\n IArkosRoute,\n InternalIArkosRouter,\n PathParams,\n} from \"../../types\";\nimport RouteConfigValidator from \"../../route-config-validator\";\nimport { applyPrefix, getMiddlewareStack } from \".\";\nimport { getUserFileExtension } from \"../../../helpers/fs.helpers\";\nimport { getArkosConfig } from \"../../../../server\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\nimport deepmerge from \"../../../helpers/deepmerge.helper\";\nimport ExitError from \"../../../helpers/exit-error\";\nimport uploadManager from \"./upload-manager\";\nimport { ArkosAnyRequestHandler } from \"../../../../types\";\n\nexport function applyArkosRouterProxy<T extends object>(\n target: T,\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n openapi?: { tags?: string[] };\n },\n component: \"app\" | \"router\" = \"router\"\n): T {\n (target as InternalIArkosRouter)._arkos = {\n options,\n routes: [],\n };\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver) as Function;\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 === \"use\") {\n return function (\n config: ArkosUseConfig | PathParams | ArkosAnyRequestHandler,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n // normalize function/router to ArkosUseConfig\n if (typeof config === \"function\" || Array.isArray(config)) {\n handlers = [config as ArkosAnyRequestHandler, ...handlers];\n config = {} as ArkosUseConfig;\n } else if (\n !config ||\n typeof config !== \"object\" ||\n typeof config === \"string\" ||\n config instanceof RegExp\n ) {\n throw ExitError(\n `First argument of ${component}.use() must be a valid ArkosRouteConfig object or a middleware function, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}.`\n );\n }\n\n if ((config as ArkosUseConfig).disabled) return;\n\n const useConfig = config as ArkosUseConfig;\n const path = applyPrefix(options?.prefix, useConfig.path ?? \"/\");\n\n const arkosConfig = getArkosConfig();\n const authenticationConfig = arkosConfig.authentication;\n\n if (useConfig.authentication && !authenticationConfig?.mode)\n throw ExitError(\n `Trying to authenticate route use${path ? ` ${path}` : \"\"} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n const middlewareStack = getMiddlewareStack(useConfig);\n const allHandlers = [...middlewareStack, ...handlers];\n\n return originalMethod.call(target, path, ...allHandlers);\n };\n }\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 if (typeof config === \"function\" || Array.isArray(config))\n throw ExitError(\n `First argument of ${component}.route(\"${path}\").${method}() must be a valid ArkosRouteConfig object without path field, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const fullConfig: ArkosRouteConfig = {\n ...config,\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\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 || !RouteConfigValidator.isArkosRouteConfig(config))\n throw ExitError(\n `First argument of ${component}.${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 if (config?.disabled) return;\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = {\n ...config,\n ...(options?.openapi\n ? {\n experimental: {\n ...config?.experimental,\n openapi: deepmerge(\n options.openapi || {},\n config?.experimental?.openapi || {}\n ),\n },\n }\n : {}),\n path,\n };\n\n if ([null, undefined].includes(path as any))\n throw new 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 ExitError(\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 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 (target as InternalIArkosRouter)._arkos.routes.push({\n handler: finalHandler,\n config,\n method,\n });\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 ExitError(\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 ExitError(\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 ExitError(\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/setup.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (handlers.length === 0)\n throw ExitError(\n `No handlers provided for route ${method.toUpperCase()} ${path}.`\n );\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 });\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)(`tsc -p ${tempTsconfigPath}`, {
93
+ (0, child_process_1.execFileSync)("tsc", ["-p", tempTsconfigPath], {
94
94
  stdio: "inherit",
95
95
  cwd: process.cwd(),
96
96
  });
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"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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 process.env.NO_CLI = \"true\";\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\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 try {\n if (fs.existsSync(tsconfigPath)) {\n tsconfig = bundler.readJsonWithComments(tsconfigPath);\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"]}
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":";;;;;AAuBA,oCAmCC;AA1DD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAuD;AACvD,sDAA6D;AAC7D,sDAA6D;AAC7D,8DAA8E;AAC9E,mDAA2B;AAC3B,kFAAyD;AACzD,8CAA0C;AAC1C,wCAAqC;AAErC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAAK,CAAU,CAAC;AAW7C,SAAgB,YAAY,CAAC,UAAwB,EAAE;IACrD,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;IAC5B,MAAM,OAAO,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACvC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,IAAI,CAAC,OAAO,CAAC,G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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 { execFileSync, 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 process.env.NO_CLI = \"true\";\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\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 try {\n if (fs.existsSync(tsconfigPath)) {\n tsconfig = bundler.readJsonWithComments(tsconfigPath);\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 execFileSync(\"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"]}
@@ -19,6 +19,6 @@ function killServerChildProcess() {
19
19
  (0, start_1.killProductionServerChildProcess)();
20
20
  }
21
21
  function getVersion() {
22
- return "1.6.2-beta";
22
+ return "1.6.3-canary.2";
23
23
  }
24
24
  //# sourceMappingURL=cli.helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,sCAAsC,CAAC;AAC9C,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AAEzC,OAAO,aAAa,EAAE,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,mBAAmB,MAAM,yCAAyC,CAAC;AAC1E,OAAO,EAAmB,MAAM,EAAkB,MAAM,MAAM,CAAC;AAC/D,OAAO,SAAS,MAAM,4BAA4B,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,6DAA6D,CAAC;AACpG,OAAO,EACL,YAAY,EACZ,mBAAmB,GACpB,MAAM,sCAAsC,CAAC;AAC9C,MAAM,CAAC,MAAM,GAAG,GAAoB,OAAO,EAAE,CAAC;AAE9C,IAAI,SAAgE,CAAC;AACrE,MAAM,QAAQ,GACZ,8EAA8E,CAAC;AACjF,IAAI,YAAY,GAAG,KAAK,CAAC;AAwCzB,MAAM,UAAU,KAAK;IACnB,IAAI,OAAO,CAAC,GAAG,CAAC,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IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;QAEJ,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IAEF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,UAAU,YAAY;IAC1B,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import \"./utils/helpers/arkos-config.helpers\"; // just to trigger loading of arkos config\nimport express from \"express\";\nimport setupApp from \"./utils/setup-app\";\nimport { Arkos } from \"./types/arkos\";\nimport initializeApp, { addGlobalErrorHandler } from \"./utils/initialize-app\";\nimport { Express } from \"express\";\nimport { logAppStartup } from \"./server\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport runtimeCliCommander from \"./utils/cli/utils/runtime-cli-commander\";\nimport { IncomingMessage, Server, ServerResponse } from \"http\";\nimport ExitError from \"./utils/helpers/exit-error\";\nimport { applyArkosRouterProxy } from \"./utils/arkos-router/utils/helpers/apply-arkos-router-proxy\";\nimport {\n isProduction,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nexport const app: express.Express = express();\n\nlet appServer: Server<typeof IncomingMessage, typeof ServerResponse>;\nconst docsLink =\n \"https://www.arkosjs.com/docs/core-concepts/routing/setup#setting-up-your-app\";\nlet instanciated = false;\n\n/**\n * Creates and configures an Arkos application instance.\n *\n * Arkos extends Express with a small set of methods for registering routers,\n * loading route/service hooks, and booting the application. All Arkos-specific\n * setup (`app.build()`) must happen before the app starts\n * accepting requests.\n *\n * @example\n * ```ts\n * // Simple setup\n * import arkos from \"arkos\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * app.listen();\n * ```\n *\n * @example\n * ```ts\n * // Custom HTTP server (e.g. for WebSockets)\n * import arkos from \"arkos\";\n * import http from \"http\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * await app.build();\n *\n * const server = http.createServer(app);\n * app.listen(server)\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport function arkos(): Arkos {\n if (process.env.__ARKOS_CLI !== \"true\")\n throw ExitError(\n `Arkos.js application must be started the built-in cli ${isProduction() ? \"'arkos start' in production\" : `'arkos dev' in development`} see https://www.arkosjs.com/docs/getting-started/installation#7-set-up-packagejson-scripts`\n );\n\n if (instanciated)\n throw ExitError(`arkos() must be called only once, see ${docsLink}`);\n\n const app = applyArkosRouterProxy(express(), {}, \"app\") as any as Arkos;\n setupApp(app);\n instanciated = true;\n\n type AppState = \"idle\" | \"building\" | \"built\" | \"listening\";\n let state: AppState = \"idle\";\n\n async function loadApp() {\n await Promise.all([loadPrismaModule(), loadAllModuleComponents()]);\n let _app = initializeApp(app);\n _app = addGlobalErrorHandler(_app);\n\n if (process.env.CLI_COMMAND) await runtimeCliCommander.handle();\n return _app;\n }\n\n app.build = async function () {\n if (state === \"built\" || state === \"building\")\n throw ExitError(`app.build() must only be called once, see ${docsLink}`);\n if (state === \"listening\")\n throw ExitError(\n `app.build() must be called before app.listen(), see ${docsLink}`\n );\n\n state = \"building\";\n const _app = await loadApp();\n state = \"built\";\n return _app;\n };\n\n const originalListen = app.listen.bind(app) as any as Express[\"listen\"];\n type UserCallback = (err?: Error) => void;\n\n const defaultCb = (\n port: number | string,\n host: string,\n cb?: UserCallback\n ) => {\n logAppStartup(port, host);\n return cb || function () {};\n };\n\n app.listen = async function (...args): Promise<Server> {\n process.env.__ARKOS_SERVER_LISTENER = \"arkos\";\n\n if (state === \"listening\")\n throw ExitError(`app.listen() must only be called once, see ${docsLink}`);\n if (state === \"building\")\n throw ExitError(\n `app.build() must be awaited before calling app.listen(), see ${docsLink}`\n );\n\n if (state === \"idle\") {\n state = \"listening\";\n await loadApp();\n }\n\n validateArkosConfig();\n\n const port = Number(process.env.__PORT || process.env.PORT || \"8000\");\n const host = process.env.__HOST! || process.env.HOST || \"0.0.0.0\";\n\n if ((args as any)?.length === 0 || typeof args[0] === \"function\")\n appServer = originalListen(\n port,\n host,\n defaultCb(port, host, args[0] as UserCallback)\n );\n else if (args[0] instanceof Server || typeof args[0] === \"object\")\n appServer = args[0].listen(\n port,\n host,\n defaultCb(port, host, args[1] as UserCallback)\n );\n\n return appServer;\n };\n\n return app;\n}\n\nexport function getAppServer() {\n return appServer;\n}\n"]}
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,sCAAsC,CAAC;AAC9C,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AAEzC,OAAO,aAAa,EAAE,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,mBAAmB,MAAM,yCAAyC,CAAC;AAC1E,OAAO,EAAmB,MAAM,EAAkB,MAAM,MAAM,CAAC;AAC/D,OAAO,SAAS,MAAM,4BAA4B,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,6DAA6D,CAAC;AACpG,OAAO,EACL,YAAY,EACZ,mBAAmB,GACpB,MAAM,sCAAsC,CAAC;AAC9C,MAAM,CAAC,MAAM,GAAG,GAAoB,OAAO,EAAE,CAAC;AAE9C,IAAI,SAAgE,CAAC;AACrE,MAAM,QAAQ,GACZ,8EAA8E,CAAC;AACjF,IAAI,YAAY,GAAG,KAAK,CAAC;AAwCzB,MAAM,UAAU,KAAK;IACnB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QACpC,MAAM,SAAS,CACb,yDAAyD,YAAY,EAAE,CAAC,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC,4BAA4B,6FAA6F,CACp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AC,CAAC;IAEF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,UAAU,YAAY;IAC1B,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import \"./utils/helpers/arkos-config.helpers\"; // just to trigger loading of arkos config\nimport express from \"express\";\nimport setupApp from \"./utils/setup-app\";\nimport { Arkos } from \"./types/arkos\";\nimport initializeApp, { addGlobalErrorHandler } from \"./utils/initialize-app\";\nimport { Express } from \"express\";\nimport { logAppStartup } from \"./server\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport runtimeCliCommander from \"./utils/cli/utils/runtime-cli-commander\";\nimport { IncomingMessage, Server, ServerResponse } from \"http\";\nimport ExitError from \"./utils/helpers/exit-error\";\nimport { applyArkosRouterProxy } from \"./utils/arkos-router/utils/helpers/apply-arkos-router-proxy\";\nimport {\n isProduction,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nexport const app: express.Express = express();\n\nlet appServer: Server<typeof IncomingMessage, typeof ServerResponse>;\nconst docsLink =\n \"https://www.arkosjs.com/docs/core-concepts/routing/setup#setting-up-your-app\";\nlet instanciated = false;\n\n/**\n * Creates and configures an Arkos application instance.\n *\n * Arkos extends Express with a small set of methods for registering routers,\n * loading route/service hooks, and booting the application. All Arkos-specific\n * setup (`app.build()`) must happen before the app starts\n * accepting requests.\n *\n * @example\n * ```ts\n * // Simple setup\n * import arkos from \"arkos\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * app.listen();\n * ```\n *\n * @example\n * ```ts\n * // Custom HTTP server (e.g. for WebSockets)\n * import arkos from \"arkos\";\n * import http from \"http\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * await app.build();\n *\n * const server = http.createServer(app);\n * app.listen(server)\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport function arkos(): Arkos {\n if (process.env.__ARKOS_CLI !== \"true\")\n throw ExitError(\n `Arkos.js application must be started the built-in cli ${isProduction() ? \"'arkos start' in production\" : `'arkos dev' in development`} see https://www.arkosjs.com/docs/getting-started/installation#7-set-up-packagejson-scripts`\n );\n\n if (instanciated)\n throw ExitError(`arkos() must be called only once, see ${docsLink}`);\n\n const app = applyArkosRouterProxy(express(), {}, \"app\") as any as Arkos;\n setupApp(app);\n instanciated = true;\n\n type AppState = \"idle\" | \"building\" | \"built\" | \"listening\";\n let state: AppState = \"idle\";\n\n async function loadApp() {\n await Promise.all([loadPrismaModule(), loadAllModuleComponents()]);\n let _app = initializeApp(app);\n _app = addGlobalErrorHandler(_app);\n\n if (process.env.CLI_COMMAND) await runtimeCliCommander.handle();\n return _app;\n }\n\n app.build = async function () {\n if (state === \"built\" || state === \"building\")\n throw ExitError(`app.build() must only be called once, see ${docsLink}`);\n if (state === \"listening\")\n throw ExitError(\n `app.build() must be called before app.listen(), see ${docsLink}`\n );\n\n state = \"building\";\n const _app = await loadApp();\n state = \"built\";\n return _app;\n };\n\n const originalListen = app.listen.bind(app) as any as Express[\"listen\"];\n type UserCallback = (err?: Error) => void;\n\n const defaultCb = (\n port: number | string,\n host: string,\n cb?: UserCallback\n ) => {\n logAppStartup(port, host);\n return cb || function () {};\n };\n\n app.listen = async function (...args: any[]): Promise<Server> {\n process.env.__ARKOS_SERVER_LISTENER = \"arkos\";\n\n if (state === \"listening\")\n throw ExitError(`app.listen() must only be called once, see ${docsLink}`);\n if (state === \"building\")\n throw ExitError(\n `app.build() must be awaited before calling app.listen(), see ${docsLink}`\n );\n\n if (state === \"idle\") {\n state = \"listening\";\n await loadApp();\n }\n\n validateArkosConfig();\n\n const port = Number(process.env.__PORT || process.env.PORT || \"8000\");\n const host = process.env.__HOST! || process.env.HOST || \"0.0.0.0\";\n\n if ((args as any)?.length === 0 || typeof args[0] === \"function\")\n appServer = originalListen(\n port,\n host,\n defaultCb(port, host, args[0] as UserCallback)\n );\n else if (args[0] instanceof Server || typeof args[0] === \"object\")\n appServer = args[0].listen(\n port,\n host,\n defaultCb(port, host, args[1] as UserCallback)\n );\n\n return appServer;\n };\n\n return app;\n}\n\nexport function getAppServer() {\n return appServer;\n}\n"]}
@@ -6,6 +6,10 @@ import catchAsync from "../error-handler/utils/catch-async.js";
6
6
  import { getArkosConfig } from "../../server.js";
7
7
  import { processFile, processImage } from "./utils/helpers/file-upload.helpers.js";
8
8
  import { getModuleComponents } from "../../utils/dynamic-loader.js";
9
+ function matchesUploadUrl(originalUrl, baseUploadRoute, fileType, fileName) {
10
+ const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;
11
+ return originalUrl === expectedPath || originalUrl.startsWith(expectedPath);
12
+ }
9
13
  export class FileUploadController {
10
14
  constructor() {
11
15
  this.uploadFile = catchAsync(async (req, res, next) => {
@@ -106,10 +110,11 @@ export class FileUploadController {
106
110
  default:
107
111
  return next(new AppError("Invalid file type", 400, "InvalidFileType"));
108
112
  }
113
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
109
114
  try {
110
115
  const { fileUpload } = getArkosConfig();
111
116
  const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
112
- const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
117
+ const urlPattern = new RegExp(`${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`);
113
118
  const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
114
119
  if (isExpectedUrlPattern) {
115
120
  const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
@@ -171,9 +176,7 @@ export class FileUploadController {
171
176
  return next(new AppError("No new file uploaded", 400, "MissingNewFile"));
172
177
  if (fileName && fileName.trim() !== "") {
173
178
  try {
174
- const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
175
- const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
176
- const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
179
+ const isExpectedUrlPattern = matchesUploadUrl(req.originalUrl, fileUpload?.baseRoute || "/api/uploads", fileType, fileName);
177
180
  if (isExpectedUrlPattern) {
178
181
  const oldFileUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
179
182
  await uploader.deleteFileByUrl(oldFileUrl);
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEhF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAKjE,MAAM,OAAO,oBAAoB;IAAjC;QAeE,eAAU,GAAG,UAAU,CACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,mBAAmB,CAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,qBAAqB,EAAE,CAAC;YAE5B,MAAM,EAAE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\"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
1
+ {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC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,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,8BAA8B,IAAI,CAAC,MAAM,qBAAqB;4BAChE,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,8BAA8B;wBAChD,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,2BAA2B;4BAC7B,CAAC,CAAC,4BAA4B;iBACnC,CAAC;gBAEF,IAAI,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,CAAC;oBACrC,GAAW,CAAC,YAAY,GAAG,WAAW,CAAC;oBACxC,GAAG,CAAC,YAAY,GAAG,WAAW,CAAC;oBAC/B,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;oBAC7B,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC;oBAClC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\nfunction matchesUploadUrl(\n originalUrl: string,\n baseUploadRoute: string,\n fileType: string,\n fileName: string\n): boolean {\n const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;\n return originalUrl === expectedPath || originalUrl.startsWith(expectedPath);\n}\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n // top of file or a shared utils import\n const escapeRegExp = (value: string) =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n try {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const isExpectedUrlPattern = matchesUploadUrl(\n req.originalUrl,\n fileUpload?.baseRoute || \"/api/uploads\",\n fileType,\n fileName\n );\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"AA8JA,MAAM,CAAN,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,KAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n // /**\n // * Request signals used to control Arkos's built-in request handling pipeline.\n // *\n // * @since v1.6.0-beta\n // */\n // signals?: {\n // /**\n // * When set to `true` in a `before` hook, Arkos skips its built-in logic for the current pipeline step (e.g. CRUD, authentication, authorization).\n // * Automatically reset to `false` after the step completes.\n // *\n // * @example\n // * ```ts\n // * before: (req, res, next) => {\n // * req.user = myCustomAuth(req);\n // * req.signals.skip = true;\n // * next();\n // * }\n // * ```\n // */\n // skip?: boolean;\n // };\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `multer.single()`\n */\n file?: Express.Multer.File;\n /**\n * Uploaded files, populated when using `multer.array()` or `multer.fields()`.\n *\n */\n files?: Express.Multer.File[] | Record<string, Express.Multer.File[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"AA8JA,MAAM,CAAN,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,KAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n // /**\n // * Request signals used to control Arkos's built-in request handling pipeline.\n // *\n // * @since v1.6.0-beta\n // */\n // signals?: {\n // /**\n // * When set to `true` in a `before` hook, Arkos skips its built-in logic for the current pipeline step (e.g. CRUD, authentication, authorization).\n // * Automatically reset to `false` after the step completes.\n // *\n // * @example\n // * ```ts\n // * before: (req, res, next) => {\n // * req.user = myCustomAuth(req);\n // * req.signals.skip = true;\n // * next();\n // * }\n // * ```\n // */\n // skip?: boolean;\n // };\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `multer.single()`\n */\n file?: Express.Multer.File;\n /**\n * Uploaded files, populated when using `multer.array()` or `multer.fields()`.\n *\n */\n files?: Express.Multer.File[] | Record<string, Express.Multer.File[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosAnyRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> =\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | Array<\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n >;\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=validator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validator.js","sourceRoot":"","sources":["../../../../src/types/validation/validator.ts"],"names":[],"mappings":"","sourcesContent":["import { ZodSchema } from \"zod\";\n\nexport type Validator =\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import {\n IRoute,\n IRouter,\n IRouterHandler,\n IRouterMatcher,\n Locals,\n} from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { ArkosRouterOptions } from \"..\";\n\nexport type ArkosUseConfig = Pick<\n ArkosRouteConfig,\n | \"authentication\"\n | \"rateLimit\"\n | \"compression\"\n | \"queryParser\"\n | \"bodyParser\"\n | \"disabled\"\n> & {\n path?: PathParams; // optional unlike ArkosRouteConfig where path is required\n};\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type InternalIArkosRouter = IArkosRouter & {\n _arkos: {\n options?: ArkosRouterOptions;\n routes: Array<{\n handler: ArkosAnyRequestHandler;\n config: ArkosRouteConfig;\n method: string;\n }>;\n };\n};\n\nexport type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>;\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n };\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | null\n | false\n | undefined = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\n/**\n * Handler function for `use` that accepts route configuration and middleware handlers.\n *\n * @param {ArkosUseConfig} config - The use configuration object or path.\n * @param {...ArkosAnyRequestHandler} handlers - Middleware handlers.\n * @returns {T} The router instance.\n */\n\nexport type UseMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (\n config: ArkosUseConfig,\n ...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n ArkosErrorRequestHandler | Array<ArkosErrorRequestHandler>\n >\n ): T;\n (...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>): T;\n };\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\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 interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n use: UseMethodHandler<this>;\n\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | null\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | null\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | null\n | undefined = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\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?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import {\n IRoute,\n IRouter,\n IRouterHandler,\n IRouterMatcher,\n Locals,\n} from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport {\n ArkosAnyRequestHandler,\n ArkosErrorRequestHandler,\n ArkosRequestHandler,\n} from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { ArkosRouterOptions } from \"..\";\nimport { Validator } from \"../../../types/validation/validator\";\n\nexport type ArkosUseConfig = Pick<\n ArkosRouteConfig,\n | \"authentication\"\n | \"rateLimit\"\n | \"compression\"\n | \"queryParser\"\n | \"bodyParser\"\n | \"disabled\"\n> & {\n path?: PathParams; // optional unlike ArkosRouteConfig where path is required\n};\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type InternalIArkosRouter = IArkosRouter & {\n _arkos: {\n options?: ArkosRouterOptions;\n routes: Array<{\n handler: ArkosAnyRequestHandler;\n config: ArkosRouteConfig;\n method: string;\n }>;\n };\n};\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n // (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n };\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\n/**\n * Handler function for `use` that accepts route configuration and middleware handlers.\n *\n * @param {ArkosUseConfig} config - The use configuration object or path.\n * @param {...ArkosAnyRequestHandler} handlers - Middleware handlers.\n * @returns {T} The router instance.\n */\n\nexport type UseMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (\n config: ArkosUseConfig,\n ...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n ArkosErrorRequestHandler | Array<ArkosErrorRequestHandler>\n >\n ): T;\n (...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>): T;\n };\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\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 interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n use: UseMethodHandler<this>;\n\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\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?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"apply-arkos-router-proxy.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.ts"],"names":[],"mappings":"AASA,OAAO,oBAAoB,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,WAAW,EA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D,CACzE,CAAC;oBAEJ,QAAQ,GAAG,CAAC,GAAG,kBAAkB,CAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAExD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;wBACvB,MAAM,SAAS,CACb,kCAAkC,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,GAAG,CAClE,CAAC;oBAEJ,IACE,MAAM,CAAC,YAAY,EAAE,OAAO;wBAC5B,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,KAAK,KAAK;wBAEnD,QAAQ,CAAC,IAAI,CACX,UAAU,CACR,aAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,EAC5D,EAAE,IAAI,EAAE,OAAO,EAAE,CAClB,CACF,CAAC;oBAEJ,OAAO,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBACxD,CAAC,CAAC;YACJ,CAAC;YAED,OAAO,cAAc,CAAC;QACxB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { RouterOptions } from \"express\";\nimport {\n ArkosAnyRequestHandler,\n ArkosRouteConfig,\n ArkosUseConfig,\n IArkosRoute,\n InternalIArkosRouter,\n PathParams,\n} from \"../../types\";\nimport RouteConfigValidator from \"../../route-config-validator\";\nimport { applyPrefix, getMiddlewareStack } from \".\";\nimport { getUserFileExtension } from \"../../../helpers/fs.helpers\";\nimport { getArkosConfig } from \"../../../../server\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\nimport deepmerge from \"../../../helpers/deepmerge.helper\";\nimport ExitError from \"../../../helpers/exit-error\";\nimport uploadManager from \"./upload-manager\";\n\nexport function applyArkosRouterProxy<T extends object>(\n target: T,\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n openapi?: { tags?: string[] };\n },\n component: \"app\" | \"router\" = \"router\"\n): T {\n (target as InternalIArkosRouter)._arkos = {\n options,\n routes: [],\n };\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver) as Function;\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 === \"use\") {\n return function (\n config: ArkosUseConfig | PathParams | ArkosAnyRequestHandler,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n // normalize function/router to ArkosUseConfig\n if (typeof config === \"function\" || Array.isArray(config)) {\n handlers = [config as ArkosAnyRequestHandler, ...handlers];\n config = {} as ArkosUseConfig;\n } else if (\n !config ||\n typeof config !== \"object\" ||\n typeof config === \"string\" ||\n config instanceof RegExp\n ) {\n throw ExitError(\n `First argument of ${component}.use() must be a valid ArkosRouteConfig object or a middleware function, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}.`\n );\n }\n\n if ((config as ArkosUseConfig).disabled) return;\n\n const useConfig = config as ArkosUseConfig;\n const path = applyPrefix(options?.prefix, useConfig.path ?? \"/\");\n\n const arkosConfig = getArkosConfig();\n const authenticationConfig = arkosConfig.authentication;\n\n if (useConfig.authentication && !authenticationConfig?.mode)\n throw ExitError(\n `Trying to authenticate route use${path ? ` ${path}` : \"\"} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n const middlewareStack = getMiddlewareStack(useConfig);\n const allHandlers = [...middlewareStack, ...handlers];\n\n return originalMethod.call(target, path, ...allHandlers);\n };\n }\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 if (typeof config === \"function\" || Array.isArray(config))\n throw ExitError(\n `First argument of ${component}.route(\"${path}\").${method}() must be a valid ArkosRouteConfig object without path field, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const fullConfig: ArkosRouteConfig = {\n ...config,\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\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 || !RouteConfigValidator.isArkosRouteConfig(config))\n throw ExitError(\n `First argument of ${component}.${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 if (config?.disabled) return;\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = {\n ...config,\n ...(options?.openapi\n ? {\n experimental: {\n ...config?.experimental,\n openapi: deepmerge(\n options.openapi || {},\n config?.experimental?.openapi || {}\n ),\n },\n }\n : {}),\n path,\n };\n\n if ([null, undefined].includes(path as any))\n throw new 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 ExitError(\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 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 (target as InternalIArkosRouter)._arkos.routes.push({\n handler: finalHandler,\n config,\n method,\n });\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 ExitError(\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 ExitError(\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 ExitError(\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/setup.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (handlers.length === 0)\n throw ExitError(\n `No handlers provided for route ${method.toUpperCase()} ${path}.`\n );\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 });\n}\n"]}
1
+ {"version":3,"file":"apply-arkos-router-proxy.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.ts"],"names":[],"mappings":"AAQA,OAAO,oBAAoB,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,GAAG,CAAC;AACpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,mBAAmB,MAAM,6BAA6B,CAA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AkC,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,GAAG,CAClE,CAAC;oBAEJ,IACE,MAAM,CAAC,YAAY,EAAE,OAAO;wBAC5B,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,KAAK,KAAK;wBAEnD,QAAQ,CAAC,IAAI,CACX,UAAU,CACR,aAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,EAC5D,EAAE,IAAI,EAAE,OAAO,EAAE,CAClB,CACF,CAAC;oBAEJ,OAAO,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBACxD,CAAC,CAAC;YACJ,CAAC;YAED,OAAO,cAAc,CAAC;QACxB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { RouterOptions } from \"express\";\nimport {\n ArkosRouteConfig,\n ArkosUseConfig,\n IArkosRoute,\n InternalIArkosRouter,\n PathParams,\n} from \"../../types\";\nimport RouteConfigValidator from \"../../route-config-validator\";\nimport { applyPrefix, getMiddlewareStack } from \".\";\nimport { getUserFileExtension } from \"../../../helpers/fs.helpers\";\nimport { getArkosConfig } from \"../../../../server\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\nimport deepmerge from \"../../../helpers/deepmerge.helper\";\nimport ExitError from \"../../../helpers/exit-error\";\nimport uploadManager from \"./upload-manager\";\nimport { ArkosAnyRequestHandler } from \"../../../../types\";\n\nexport function applyArkosRouterProxy<T extends object>(\n target: T,\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n openapi?: { tags?: string[] };\n },\n component: \"app\" | \"router\" = \"router\"\n): T {\n (target as InternalIArkosRouter)._arkos = {\n options,\n routes: [],\n };\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver) as Function;\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 === \"use\") {\n return function (\n config: ArkosUseConfig | PathParams | ArkosAnyRequestHandler,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n // normalize function/router to ArkosUseConfig\n if (typeof config === \"function\" || Array.isArray(config)) {\n handlers = [config as ArkosAnyRequestHandler, ...handlers];\n config = {} as ArkosUseConfig;\n } else if (\n !config ||\n typeof config !== \"object\" ||\n typeof config === \"string\" ||\n config instanceof RegExp\n ) {\n throw ExitError(\n `First argument of ${component}.use() must be a valid ArkosRouteConfig object or a middleware function, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}.`\n );\n }\n\n if ((config as ArkosUseConfig).disabled) return;\n\n const useConfig = config as ArkosUseConfig;\n const path = applyPrefix(options?.prefix, useConfig.path ?? \"/\");\n\n const arkosConfig = getArkosConfig();\n const authenticationConfig = arkosConfig.authentication;\n\n if (useConfig.authentication && !authenticationConfig?.mode)\n throw ExitError(\n `Trying to authenticate route use${path ? ` ${path}` : \"\"} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n const middlewareStack = getMiddlewareStack(useConfig);\n const allHandlers = [...middlewareStack, ...handlers];\n\n return originalMethod.call(target, path, ...allHandlers);\n };\n }\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 if (typeof config === \"function\" || Array.isArray(config))\n throw ExitError(\n `First argument of ${component}.route(\"${path}\").${method}() must be a valid ArkosRouteConfig object without path field, but received ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const fullConfig: ArkosRouteConfig = {\n ...config,\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\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 || !RouteConfigValidator.isArkosRouteConfig(config))\n throw ExitError(\n `First argument of ${component}.${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 if (config?.disabled) return;\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = {\n ...config,\n ...(options?.openapi\n ? {\n experimental: {\n ...config?.experimental,\n openapi: deepmerge(\n options.openapi || {},\n config?.experimental?.openapi || {}\n ),\n },\n }\n : {}),\n path,\n };\n\n if ([null, undefined].includes(path as any))\n throw new 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 ExitError(\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 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 (target as InternalIArkosRouter)._arkos.routes.push({\n handler: finalHandler,\n config,\n method,\n });\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 ExitError(\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 ExitError(\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 ExitError(\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/setup.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (handlers.length === 0)\n throw ExitError(\n `No handlers provided for route ${method.toUpperCase()} ${path}.`\n );\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 });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import path from "path";
2
2
  import fs from "fs";
3
- import { execSync } from "child_process";
3
+ import { execFileSync, execSync } from "child_process";
4
4
  import { getUserFileExtension } from "../helpers/fs.helpers.js";
5
5
  import { loadEnvironmentVariables } from "../dotenv.helpers.js";
6
6
  import { detectPackageManagerFromUserAgent } from "../helpers/global.helpers.js";
@@ -84,7 +84,7 @@ function buildTypeScriptProject(options, moduleType) {
84
84
  fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));
85
85
  try {
86
86
  removeDir(BUILD_DIR);
87
- execSync(`tsc -p ${tempTsconfigPath}`, {
87
+ execFileSync("tsc", ["-p", tempTsconfigPath], {
88
88
  stdio: "inherit",
89
89
  cwd: process.cwd(),
90
90
  });
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sourceRoot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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,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,EAAE,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 process.env.NO_CLI = \"true\";\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\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 try {\n if (fs.existsSync(tsconfigPath)) {\n tsconfig = bundler.readJsonWithComments(tsconfigPath);\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"]}
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,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,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 { execFileSync, 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 process.env.NO_CLI = \"true\";\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\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 try {\n if (fs.existsSync(tsconfigPath)) {\n tsconfig = bundler.readJsonWithComments(tsconfigPath);\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 execFileSync(\"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"]}
@@ -11,6 +11,6 @@ export function killServerChildProcess() {
11
11
  killProductionServerChildProcess();
12
12
  }
13
13
  export function getVersion() {
14
- return "1.6.2-beta";
14
+ return "1.6.3-canary.2";
15
15
  }
16
16
  //# sourceMappingURL=cli.helpers.js.map
@@ -235,4 +235,5 @@ export interface ArkosNextFunction extends NextFunction {
235
235
  }
236
236
  export type ArkosRequestHandler<P extends Record<string, any> = any, ResBody = any, ReqBody = any, ReqQuery extends Record<string, any> = any, Locals extends Record<string, any> = Record<string, any>> = (req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>, res: ArkosResponse<ResBody, Locals>, next: ArkosNextFunction) => void | Promise<void>;
237
237
  export type ArkosErrorRequestHandler<P extends Record<string, any> = any, ResBody = any, ReqBody = any, ReqQuery extends Record<string, any> = any, Locals extends Record<string, any> = Record<string, any>> = (err: any, req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>, res: ArkosResponse<ResBody, Locals>, next: ArkosNextFunction) => void | Promise<void>;
238
+ export type ArkosAnyRequestHandler<P extends Record<string, any> = any, ResBody = any, ReqBody = any, ReqQuery extends Record<string, any> = any, Locals extends Record<string, any> = Record<string, any>> = ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals> | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals> | Array<ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals> | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>>;
238
239
  export {};
@@ -0,0 +1,2 @@
1
+ import { ZodSchema } from "zod";
2
+ export type Validator = ZodSchema | (new (...args: any[]) => object) | null | false;
@@ -3,12 +3,13 @@ import { z, ZodSchema } from "zod";
3
3
  import { Options as RateLimitOptions } from "express-rate-limit";
4
4
  import { Options as QueryParserOptions } from "../../../utils/helpers/query-parser.helpers";
5
5
  import { DetailedAccessControlRule } from "../../../types/auth";
6
- import { ArkosErrorRequestHandler, ArkosRequestHandler } from "../../../types";
6
+ import { ArkosAnyRequestHandler, ArkosErrorRequestHandler, ArkosRequestHandler } from "../../../types";
7
7
  import compression from "compression";
8
8
  import { OpenApiConfig } from "./openapi-config";
9
9
  import { UploadConfig } from "./upload-config";
10
10
  import { BodyParserConfig } from "./body-parser-config";
11
11
  import { ArkosRouterOptions } from "..";
12
+ import { Validator } from "../../../types/validation/validator";
12
13
  export type ArkosUseConfig = Pick<ArkosRouteConfig, "authentication" | "rateLimit" | "compression" | "queryParser" | "bodyParser" | "disabled"> & {
13
14
  path?: PathParams;
14
15
  };
@@ -24,7 +25,6 @@ export type InternalIArkosRouter = IArkosRouter & {
24
25
  }>;
25
26
  };
26
27
  };
27
- export type ArkosAnyRequestHandler = ArkosRequestHandler | ArkosErrorRequestHandler | Array<ArkosRequestHandler | ArkosErrorRequestHandler>;
28
28
  /**
29
29
  * Handler function for HTTP methods that accepts route configuration and request handlers.
30
30
  *
@@ -33,14 +33,13 @@ export type ArkosAnyRequestHandler = ArkosRequestHandler | ArkosErrorRequestHand
33
33
  * @returns {IRouter} The Express router instance.
34
34
  */
35
35
  type RouterMethodHandler<T> = IRouterHandler<T> & IRouterMatcher<T> & {
36
- (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;
37
- <TQuery extends ZodSchema | (new (...args: any[]) => object) | null | false | undefined = any, TBody extends ZodSchema | (new (...args: any[]) => object) | null | false | undefined = any, TParams extends ZodSchema | (new (...args: any[]) => object) | null | false | undefined = any>(config: ArkosRouteConfig<TQuery, TBody, TParams>, ...handlers: Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any> | Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any>>>): T;
38
- <TQuery extends ZodSchema | (new (...args: any[]) => object) | null | false | undefined = any, TBody extends ZodSchema | (new (...args: any[]) => object) | null | false | undefined = any, TParams extends ZodSchema | (new (...args: any[]) => object) | null | false | undefined = any>(config: ArkosRouteConfig<TQuery, TBody, TParams>, ...handlers: Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any> | Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any>>>): T;
36
+ <TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: ArkosRouteConfig<TQuery, TBody, TParams>, ...handlers: Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any> | Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any>>>): T;
37
+ <TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: ArkosRouteConfig<TQuery, TBody, TParams>, ...handlers: Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any> | Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any>>>): T;
39
38
  };
40
39
  export type ArkosRouteMethodHandler<T> = {
41
40
  (config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, "path">, ...handlers: Array<ArkosRequestHandler | ArkosErrorRequestHandler | Array<ArkosRequestHandler | ArkosErrorRequestHandler>>): T;
42
- <TQuery extends ZodSchema | (new (...args: any[]) => object) | null | null | false | undefined = any, TBody extends ZodSchema | (new (...args: any[]) => object) | null | null | false | undefined = any, TParams extends ZodSchema | (new (...args: any[]) => object) | null | null | false | undefined = any>(config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, "path">, ...handlers: Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals> | Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals>>>): T;
43
- <TQuery extends ZodSchema | (new (...args: any[]) => object) | null | null | false | undefined = any, TBody extends ZodSchema | (new (...args: any[]) => object) | null | null | false | undefined = any, TParams extends ZodSchema | (new (...args: any[]) => object) | null | null | false | undefined = any>(config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, "path">, ...handlers: Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals> | Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals>>>): T;
41
+ <TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, "path">, ...handlers: Array<ArkosAnyRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals> | Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals>>>): T;
42
+ <TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, "path">, ...handlers: Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals> | Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals>>>): T;
44
43
  };
45
44
  /**
46
45
  * Handler function for `use` that accepts route configuration and middleware handlers.
@@ -122,7 +121,7 @@ export interface IArkosRouter extends IRouter {
122
121
  /**
123
122
  * Configuration object for defining routes in Arkos.js.
124
123
  */
125
- export type ArkosRouteConfig<TQuery extends ZodSchema | (new (...args: any[]) => object) | null | false | null | undefined = any, TBody extends ZodSchema | (new (...args: any[]) => object) | null | false | null | undefined = any, TParams extends ZodSchema | (new (...args: any[]) => object) | null | false | null | undefined = any> = {
124
+ export type ArkosRouteConfig<TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any> = {
126
125
  /**
127
126
  * Disables the route by not mounting it internally.
128
127
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkos",
3
- "version": "1.6.2-beta",
3
+ "version": "1.6.3-canary.2",
4
4
  "description": "The Express & Prisma RESTful Framework",
5
5
  "main": "dist/cjs/exports/index.js",
6
6
  "module": "dist/esm/exports/index.js",
@@ -97,7 +97,6 @@
97
97
  "test": "jest",
98
98
  "test:watch": "jest --watch",
99
99
  "test:coverage": "jest --coverage",
100
- "test:ui": "vitest --ui",
101
100
  "test:create": "tsx src/scripts/create-test.ts",
102
101
  "publish:test": "npm publish --tag test",
103
102
  "publish:beta": "npm publish --tag beta",
@@ -147,7 +146,7 @@
147
146
  "@types/jsonwebtoken": "9.0.9",
148
147
  "@types/multer": "2.0.0",
149
148
  "@types/node": "22.13.13",
150
- "@types/nodemailer": "6.4.17",
149
+ "@types/nodemailer": "8.0.0",
151
150
  "@types/pluralize": "0.0.33",
152
151
  "@types/swagger-jsdoc": "6.0.4",
153
152
  "@typescript-eslint/eslint-plugin": "6.0.0",
@@ -164,8 +163,7 @@
164
163
  "ts-prune": "0.10.3",
165
164
  "tsx": "4.20.3",
166
165
  "type-fest": "4.41.0",
167
- "typescript": "5.8.2",
168
- "vitest": "3.2.4"
166
+ "typescript": "5.8.2"
169
167
  },
170
168
  "dependencies": {
171
169
  "chokidar": "4.0.3",
@@ -190,9 +188,9 @@
190
188
  "html-to-text": "9.0.5",
191
189
  "jsonwebtoken": "9.0.3",
192
190
  "mimetype": "0.0.8",
193
- "multer": "2.0.2",
194
191
  "nodemailer": "8.0.7",
195
192
  "sharp": "0.34.5",
193
+ "multer": "2.1.1",
196
194
  "swagger-jsdoc": "6.2.8",
197
195
  "zod": "3.24.2",
198
196
  "zod-to-json-schema": "3.24.6"