arkos 2.0.0-next.13 → 2.0.0-next.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -145
- package/cli.js +1 -0
- package/dist/cjs/app.js +7 -0
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/exports/error-handler/index.js +15 -0
- package/dist/cjs/exports/error-handler/index.js.map +1 -1
- package/dist/cjs/modules/auth/auth.router.js +3 -0
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +2 -0
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +15 -3
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +19 -12
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js +5 -1
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js +9 -0
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +25 -42
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js +0 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +8 -9
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/errors.js +158 -0
- package/dist/cjs/modules/error-handler/utils/errors.js.map +1 -0
- package/dist/cjs/modules/error-handler/utils/multer-error-handler.js +39 -0
- package/dist/cjs/modules/error-handler/utils/multer-error-handler.js.map +1 -0
- package/dist/cjs/modules/file-upload/file-upload.controller.js +10 -14
- package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.router.js +2 -0
- package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +8 -2
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js +18 -0
- package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js +5 -5
- package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/cjs/types/arkos-prisma-input.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/types/router-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js +86 -28
- package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +11 -7
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/upload-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +34 -28
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +9 -6
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js +334 -77
- package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
- package/dist/cjs/utils/bundler.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +2 -3
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +11 -6
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/export-auth-action.js +5 -4
- package/dist/cjs/utils/cli/export-auth-action.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +6 -8
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +22 -19
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +4 -2
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-controller-template.js +19 -7
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js +7 -6
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js +4 -4
- package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generators.js +0 -6
- package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/cjs/utils/define-config.js +5 -0
- package/dist/cjs/utils/define-config.js.map +1 -1
- package/dist/cjs/utils/dotenv.helpers.js +0 -6
- package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
- package/dist/cjs/utils/features/api.features.js +23 -5
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/arkos-config.helpers.js +22 -2
- package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/exit-error.js +1 -0
- package/dist/cjs/utils/helpers/exit-error.js.map +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js +25 -24
- package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/global.helpers.js +3 -2
- package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +4 -5
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/url-helpers.js +14 -0
- package/dist/cjs/utils/helpers/url-helpers.js.map +1 -0
- package/dist/cjs/utils/initialize-app.js +35 -6
- package/dist/cjs/utils/initialize-app.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +12 -6
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-schema-parser.js +10 -3
- package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/cjs/utils/setup-app.js +58 -41
- package/dist/cjs/utils/setup-app.js.map +1 -1
- package/dist/esm/app.js +6 -0
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/exports/error-handler/index.js +1 -0
- package/dist/esm/exports/error-handler/index.js.map +1 -1
- package/dist/esm/modules/auth/auth.router.js +3 -0
- package/dist/esm/modules/auth/auth.router.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +2 -0
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/base/base.controller.js +15 -3
- package/dist/esm/modules/base/base.controller.js.map +1 -1
- package/dist/esm/modules/base/base.middlewares.js +19 -12
- package/dist/esm/modules/base/base.middlewares.js.map +1 -1
- package/dist/esm/modules/base/base.service.js +5 -1
- package/dist/esm/modules/base/base.service.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js +9 -0
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +22 -42
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/app-error.js +0 -1
- package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +8 -9
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/errors.js +127 -0
- package/dist/esm/modules/error-handler/utils/errors.js.map +1 -0
- package/dist/esm/modules/error-handler/utils/multer-error-handler.js +34 -0
- package/dist/esm/modules/error-handler/utils/multer-error-handler.js.map +1 -0
- package/dist/esm/modules/file-upload/file-upload.controller.js +10 -14
- package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +2 -0
- package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js +8 -2
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/get-open-api-login-html.js +18 -0
- package/dist/esm/modules/swagger/utils/get-open-api-login-html.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js +5 -5
- package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/esm/types/arkos-prisma-input.js.map +1 -1
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/types/router-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js +86 -28
- package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +11 -7
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/upload-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +34 -28
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +9 -6
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js +334 -77
- package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
- package/dist/esm/utils/bundler.js.map +1 -1
- package/dist/esm/utils/cli/build.js +3 -4
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/dev.js +12 -7
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/export-auth-action.js +5 -4
- package/dist/esm/utils/cli/export-auth-action.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +6 -8
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/index.js +22 -19
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/start.js +4 -2
- package/dist/esm/utils/cli/start.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js +16 -7
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js +7 -6
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js +4 -4
- package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generators.js +0 -6
- package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/esm/utils/define-config.js +5 -0
- package/dist/esm/utils/define-config.js.map +1 -1
- package/dist/esm/utils/dotenv.helpers.js +0 -6
- package/dist/esm/utils/dotenv.helpers.js.map +1 -1
- package/dist/esm/utils/features/api.features.js +23 -5
- package/dist/esm/utils/features/api.features.js.map +1 -1
- package/dist/esm/utils/helpers/arkos-config.helpers.js +20 -2
- package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/exit-error.js +1 -0
- package/dist/esm/utils/helpers/exit-error.js.map +1 -1
- package/dist/esm/utils/helpers/fs.helpers.js +25 -24
- package/dist/esm/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/global.helpers.js +1 -1
- package/dist/esm/utils/helpers/global.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +4 -5
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/url-helpers.js +11 -0
- package/dist/esm/utils/helpers/url-helpers.js.map +1 -0
- package/dist/esm/utils/initialize-app.js +35 -6
- package/dist/esm/utils/initialize-app.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +12 -6
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-schema-parser.js +10 -3
- package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/esm/utils/setup-app.js +59 -42
- package/dist/esm/utils/setup-app.js.map +1 -1
- package/dist/types/app.d.ts +5 -6
- package/dist/types/exports/error-handler/index.d.ts +1 -0
- package/dist/types/modules/auth/auth.service.d.ts +2 -6
- package/dist/types/modules/base/base.service.d.ts +2 -1
- package/dist/types/modules/error-handler/utils/app-error.d.ts +0 -2
- package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +1 -1
- package/dist/types/modules/error-handler/utils/errors.d.ts +176 -0
- package/dist/types/modules/error-handler/utils/multer-error-handler.d.ts +7 -0
- package/dist/types/modules/file-upload/file-upload.controller.d.ts +0 -1
- package/dist/types/modules/swagger/utils/helpers/get-swagger-default-configs.d.ts +48 -2
- package/dist/types/types/arkos-prisma-input.d.ts +3 -2
- package/dist/types/types/index.d.ts +0 -21
- package/dist/types/types/new-arkos-config.d.ts +183 -14
- package/dist/types/types/router-config.d.ts +1 -1
- package/dist/types/utils/arkos-router/arkos-router-openapi-manager.d.ts +14 -1
- package/dist/types/utils/arkos-router/index.d.ts +76 -8
- package/dist/types/utils/arkos-router/types/index.d.ts +19 -6
- package/dist/types/utils/arkos-router/types/upload-config.d.ts +63 -7
- package/dist/types/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.d.ts +1 -1
- package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +2 -0
- package/dist/types/utils/arkos-router/utils/helpers/upload-manager.d.ts +0 -36
- package/dist/types/utils/bundler.d.ts +1 -1
- package/dist/types/utils/cli/generate.d.ts +0 -1
- package/dist/types/utils/cli/start.d.ts +1 -1
- package/dist/types/utils/helpers/arkos-config.helpers.d.ts +2 -0
- package/dist/types/utils/helpers/fs.helpers.d.ts +1 -1
- package/dist/types/utils/helpers/global.helpers.d.ts +1 -0
- package/dist/types/utils/helpers/url-helpers.d.ts +1 -0
- package/dist/types/utils/prisma/prisma-schema-parser.d.ts +1 -0
- package/package.json +15 -15
- package/dist/cjs/utils/cli/utils/template-generator/templates/route-hook.template.js +0 -39
- package/dist/cjs/utils/cli/utils/template-generator/templates/route-hook.template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/service-hook.template.js +0 -32
- package/dist/cjs/utils/cli/utils/template-generator/templates/service-hook.template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/route-hook.template.js +0 -36
- package/dist/esm/utils/cli/utils/template-generator/templates/route-hook.template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/service-hook.template.js +0 -29
- package/dist/esm/utils/cli/utils/template-generator/templates/service-hook.template.js.map +0 -1
- package/dist/types/utils/cli/utils/template-generator/templates/route-hook.template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/service-hook.template.d.ts +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,SAAS,CAAC;AAGhD,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,cAAc,EAA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;4BACL,GAAG,gBAAgB,EAAE,WAAW,EAAE,OAAO;4BACzC,GAAG,CAAC,eAAe,IAAI;gCACrB,qBAAqB,EAAE;oCACrB,MAAM,EAAE,sBAAsB,CAAC,aAAa,CAC1C,yBAAyB,CAAC,eAAe,CACvC,MAAM,CAAC,YAAY,EAAE,OAAQ,EAC7B,MAAM,CACP,CACF;iCACF;6BACF,CAAC;4BACF,kBAAkB,EAAE;gCAClB,MAAM;6BACP;yBACF,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;YACJ,GAAG,CAAC,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;gBAC9D,EAAE,MAAM;gBACR,CAAC,mBAAmB;gBACpB,CAAE,MAAc,EAAE,UAAU,EAAE,IAAI;gBAClC,eAAe,IAAI;gBACjB,WAAW,EAAE;oBACX,OAAO,EAAE,CAAC,GAAG,EAAE;wBACb,MAAM,MAAM,GACV,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;4BAC1D,EAAE,MAAM,CAAC;wBAEb,OAAO;4BACL,qBAAqB,EAAE;gCACrB,MAAM,EAAE,sBAAsB,CAAC,aAAa,CAC1C,yBAAyB,CAAC,eAAe,CACvC,MAAM,EAAE,YAAY,EAAE,OAAQ,IAAI,EAAE,EACpC,MAAM,CACP,CACF;6BACF;4BACD,GAAG,gBAAgB,EAAE,WAAW,EAAE,OAAO;yBAC1C,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;SACL,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router, RouterOptions } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { extractArkosRoutes, extractPathParams } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport arkosRouterOpenApiManager from \"./arkos-router-openapi-manager\";\nimport { applyArkosRouterProxy } from \"./utils/helpers/apply-arkos-router-proxy\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n openapi?: { tags?: string[] };\n }\n): IArkosRouter {\n const router = Router(options);\n return applyArkosRouterProxy(router, options) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n let wildcardCount = (path.match(/\\*/g) || []).length;\n let wildcardIndex = 0;\n path = path.replace(/\\*/g, () => {\n wildcardIndex++;\n return wildcardCount === 1 ? \"{path}\" : `{path${wildcardIndex}}`;\n });\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpenApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\" &&\n param.name !== \"*\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n const hasUploadFields =\n Object.keys(config?.experimental?.uploads || {}).length > 0;\n const multipartFormSchema =\n convertedOpenAPI?.requestBody?.content?.[\"multipart/form-data\"];\n\n if (hasUploadFields && multipartFormSchema)\n arkosRouterOpenApiManager.validateMultipartFormDocs(\n multipartFormSchema,\n path,\n config?.experimental?.uploads\n );\n\n (paths as any)[path][method.toLowerCase()] = {\n ...convertedOpenAPI,\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: openapi.operationId || `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: (() => {\n const schema = validatorToJsonSchema(\n config?.validation?.body as any\n );\n\n return {\n ...convertedOpenAPI?.requestBody?.content,\n ...(hasUploadFields && {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config.experimental?.uploads!,\n schema\n )\n ),\n },\n }),\n \"application/json\": {\n schema,\n },\n };\n })(),\n },\n }),\n ...(convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema &&\n !multipartFormSchema &&\n !(config as any)?.validation?.body &&\n hasUploadFields && {\n requestBody: {\n content: (() => {\n const schema =\n convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema;\n\n return {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config?.experimental?.uploads! || {},\n schema\n )\n ),\n },\n ...convertedOpenAPI?.requestBody?.content,\n };\n })(),\n },\n }),\n };\n });\n\n return paths;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,SAAS,CAAC;AAGhD,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,eAAe,MAAM,oBAAoB,CAAC;AACjD,OAAO,0BAA0B,MAAM,oEAAoE,CAAC;AAC5G,OAAO,sBA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AAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router, RouterOptions } from \"express\";\nimport { IArkosRouter } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { extractArkosRoutes, extractPathParams } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport arkosRouterOpenApiManager from \"./arkos-router-openapi-manager\";\nimport { applyArkosRouterProxy } from \"./utils/helpers/apply-arkos-router-proxy\";\nimport { Arkos } from \"../../types/arkos\";\n\nexport type ArkosRouterOptions = {\n /**\n * Prefix to apply to all routes in this router.\n * Nested routers inherit and concatenate prefixes from parent routers.\n *\n * @since 1.5.0-beta\n * @example\n * // All routes in this router will be prefixed with \"/api\"\n * prefix: \"/api\"\n */\n prefix?: string | RegExp | Array<string | RegExp>;\n /**\n * OpenAPI metadata to apply to all routes in this router.\n * Nested routers inherit from parent routers unless explicitly overridden.\n * Route-level openapi config fully replaces inherited values when defined.\n *\n * @since 1.6.0-beta\n * @example\n * openapi: {\n * tags: [\"Users\"],\n * security: [{ bearerAuth: [] }]\n * }\n */\n openapi?: {\n /**\n * Tags to apply to all routes in this router, used to group them in OpenAPI documentation.\n * Route-level tags fully replaces this value when defined.\n *\n * @since 1.6.0-beta\n * @example\n * // Group all routes in this router under \"Users\"\n * tags: [\"Users\"]\n */\n tags?: string[];\n /**\n * Security requirements to apply to all routes in this router.\n * Route-level security fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * // Require bearer auth for all routes in this router\n * security: [{ bearerAuth: [] }]\n *\n * // Explicitly make all routes public (overridable per route)\n * security: []\n */\n security?: OpenAPIV3.SecurityRequirementObject[];\n\n /**\n * Server definitions to apply to all routes in this router.\n * Follows the OpenAPI 3.0 Server Object specification.\n * Route-level servers fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * servers: [{ url: \"https://api.example.com/v2\", description: \"V2 API\" }]\n */\n servers?: OpenAPIV3.ServerObject[];\n /**\n * External documentation to apply to all routes in this router.\n * Route-level externalDocs fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * externalDocs: {\n * description: \"Find more information here\",\n * url: \"https://docs.example.com/users\"\n * }\n */\n externalDocs?: OpenAPIV3.ExternalDocumentationObject;\n };\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 https://www.arkosjs.com/docs/reference/arkos-router} for configuration options\n * @since 1.4.0-beta\n */\nexport default function ArkosRouter(\n options?: RouterOptions & ArkosRouterOptions\n): IArkosRouter {\n const router = Router(options);\n return applyArkosRouterProxy(router, options) as IArkosRouter;\n}\n\nconst hasDuplicatedPath = (path: string) => /^(\\/.+)\\1/.test(path);\n\nexport function generateOpenAPIFromApp(app: Arkos) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config, routeOptions }) => {\n if (config?.experimental?.openapi === false || hasDuplicatedPath(path))\n return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n let wildcardCount = (path.match(/\\*/g) || []).length;\n let wildcardIndex = 0;\n path = path.replace(/\\*/g, () => {\n wildcardIndex++;\n return wildcardCount === 1 ? \"{path}\" : `{path${wildcardIndex}}`;\n });\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpenApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\" &&\n param.name !== \"*\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n const hasUploadFields =\n Object.keys(config?.experimental?.uploads || {}).length > 0;\n const multipartFormSchema =\n convertedOpenAPI?.requestBody?.content?.[\"multipart/form-data\"];\n\n if (hasUploadFields && multipartFormSchema)\n arkosRouterOpenApiManager.validateMultipartFormDocs(\n multipartFormSchema,\n path,\n config?.experimental?.uploads\n );\n\n (paths as any)[path][method.toLowerCase()] = {\n ...convertedOpenAPI,\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n servers: openapi?.servers || routeOptions?.openapi?.servers || undefined,\n security:\n openapi?.security || routeOptions?.openapi?.security || undefined,\n externalDocs:\n openapi?.externalDocs ||\n routeOptions?.openapi?.externalDocs ||\n undefined,\n tags: openapi?.tags || routeOptions?.openapi?.tags || [\"Defaults\"],\n operationId: openapi.operationId || `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: (() => {\n const schema = validatorToJsonSchema(\n config?.validation?.body as any\n );\n\n return {\n ...convertedOpenAPI?.requestBody?.content,\n ...(hasUploadFields && {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config.experimental?.uploads!,\n schema\n )\n ),\n },\n }),\n \"application/json\": {\n schema,\n },\n };\n })(),\n },\n }),\n ...(!multipartFormSchema &&\n !(config as any)?.validation?.body &&\n hasUploadFields && {\n requestBody: {\n content: (() => {\n const schema =\n convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema || {};\n\n return {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config?.experimental?.uploads! || {},\n schema\n )\n ),\n },\n ...convertedOpenAPI?.requestBody?.content,\n };\n })(),\n },\n }),\n } as OpenAPIV3.PathItemObject;\n });\n\n return paths;\n}\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\";\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 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 | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\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 | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\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 | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\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 | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\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 };\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 | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\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 * - 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 | {\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 { 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload-config.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/upload-config.ts"],"names":[],"mappings":"","sourcesContent":["export type UploadConfig =\n /**\n * Creates middleware that processes a single file associated with the\n * given form field.\n *\n * The `Request` object will be populated with a `file` object containing\n * information about the processed file.\n *\n * @example\n * uploads: {\n * type: \"single\",\n * field: \"avatar\",\n * uploadDir: \"images\",\n * maxSize: 1024 * 1024 * 5 // 5MB\n * }\n */\n | ({\n type: \"single\";\n /** Name of the multipart form field to process */\n field: string;\n } & ArkosRouterBaseUploadConfig)\n /**\n * Returns middleware that processes multiple files sharing the same field\n * name.\n *\n * The `Request` object will be populated with a `files` array containing\n * an information object for each processed file.\n *\n * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName`\n *\n * @example\n * uploads: {\n * type: \"array\",\n * field: \"gallery\",\n * maxCount: 10,\n * minCount: 1,\n * uploadDir: \"images\"\n * }\n */\n | ({\n type: \"array\";\n /** Shared name of the multipart form fields to process */\n field: string;\n /** Maximum number of files to process (defaults to framework config) */\n maxCount?: number;\n /** Minimum number of files required */\n
|
|
1
|
+
{"version":3,"file":"upload-config.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/upload-config.ts"],"names":[],"mappings":"","sourcesContent":["export type UploadConfig =\n /**\n * Creates middleware that processes a single file associated with the\n * given form field.\n *\n * The `Request` object will be populated with a `file` object containing\n * information about the processed file.\n *\n * @example\n * uploads: {\n * type: \"single\",\n * field: \"avatar\",\n * uploadDir: \"images\",\n * maxSize: 1024 * 1024 * 5 // 5MB\n * }\n */\n | ({\n type: \"single\";\n /** Name of the multipart form field to process. Supports bracket notation, including nested array paths (e.g. \"banners[][image]\") */\n field: string;\n } & ArkosRouterBaseUploadConfig)\n /**\n * Returns middleware that processes multiple files sharing the same field\n * name.\n *\n * The `Request` object will be populated with a `files` array containing\n * an information object for each processed file.\n *\n * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName`\n *\n * @example\n * uploads: {\n * type: \"array\",\n * field: \"gallery\",\n * maxCount: 10,\n * minCount: 1,\n * uploadDir: \"images\"\n * }\n */\n | ({\n type: \"array\";\n /** Shared name of the multipart form fields to process. Supports bracket notation, including nested array paths (e.g. \"banners[][images]\") */\n field: string;\n /** Maximum number of files to process (defaults to framework config) */\n maxCount?: number;\n /** Minimum number of files required */\n minCount?: number;\n } & ArkosRouterBaseUploadConfig)\n /**\n * Creates middleware that processes multiple files associated with the\n * given form fields.\n *\n * The `Request` object will be populated with a `files` object which\n * maps each field name to an array of the associated file information\n * objects.\n *\n * Each field entry is a full single or array upload config with a `name`\n * property. Field names support bracket notation, including nested array\n * paths (e.g. \"banners[][images]\").\n *\n * @example\n * uploads: {\n * type: \"fields\",\n * fields: [\n * { name: \"avatar\", type: \"single\", uploadDir: \"images\" },\n * { name: \"resume\", type: \"single\", uploadDir: \"documents\" },\n * { name: \"banners[][images]\", type: \"array\", maxCount: 5, uploadDir: \"banners\" }\n * ]\n * }\n */\n | ({\n type: \"fields\";\n /** Array of field configurations describing multipart form fields to process */\n fields: UploadConfigFieldEntry[];\n } & Pick<ArkosRouterBaseUploadConfig, \"deleteOnError\">)\n | ({\n type: \"fields\";\n /** Array of field configurations describing multipart form fields to process */\n fields: {\n /** Name of the form field */\n name: string;\n /** Maximum number of files for this field (defaults to framework config) */\n maxCount?: number;\n // /** Minimum number of files required for this field */\n minCount?: number;\n }[];\n } & ArkosRouterBaseUploadConfig);\n\n/**\n * A single field entry inside a `fields` upload config.\n * Each entry is a full single or array upload config with an additional\n * `name` property identifying the form field.\n *\n * Field names support bracket notation, including nested array paths\n * (e.g. \"banners[][images]\"). For nested array paths, multer validation\n * is bypassed and constraints (allowedFileTypes, maxSize, minCount, maxCount)\n * are enforced per group after upload.\n */\nexport type UploadConfigFieldEntry =\n /**\n * A single-file field entry.\n *\n * @example\n * { name: \"avatar\", type: \"single\", uploadDir: \"images\", required: true }\n *\n * @example\n * // nested array path — one image per banner\n * { name: \"banners[][image]\", type: \"single\", uploadDir: \"banners\" }\n */\n | ({\n /** Name of the form field. Supports bracket notation including nested array paths. */\n name: string;\n type: \"single\";\n } & Omit<ArkosRouterBaseUploadConfig, \"deleteOnError\">)\n /**\n * A multi-file field entry.\n *\n * @example\n * { name: \"gallery\", type: \"array\", maxCount: 6, uploadDir: \"gallery\" }\n *\n * @example\n * // nested array path — multiple images per banner, min 1 max 5\n * { name: \"banners[][images]\", type: \"array\", minCount: 1, maxCount: 5, uploadDir: \"banners\" }\n */\n | ({\n /** Name of the form field. Supports bracket notation including nested array paths. */\n name: string;\n type?: \"array\";\n /** Maximum number of files for this field (defaults to framework config) */\n maxCount?: number;\n /** Minimum number of files required for this field */\n minCount?: number;\n } & Omit<ArkosRouterBaseUploadConfig, \"deleteOnError\">); /**\n\n/**\n * Base configuration options for file uploads.\n * These settings can override framework-level defaults for specific routes.\n */\nexport type ArkosRouterBaseUploadConfig = {\n /**\n * Directory category where files will be stored.\n * Each category has its own default restrictions defined in framework config.\n *\n * @remarks Do not include the `baseUploadDir` defined under your arkos config\n * @default Depends on the file type which is descovered by the file mimetype, otherwise falls to files.\n */\n uploadDir?: string;\n /**\n * Whether to automatically delete uploaded files if an error occurs during request processing.\n * Cleanup happens when errors are thrown and not caught within the route handler.\n *\n * @default false\n */\n deleteOnError?: boolean;\n /**\n * How to attach file information to req.body for easier access in handlers and validation.\n * - \"pathname\": Just the relative path (e.g., \"images/avatar-123.jpg\")\n * - \"url\": Complete URL (e.g., \"https://api.com/uploads/images/avatar-123.jpg\")\n * - \"file\": The complete Multer file object with all metadata\n *\n * @default \"pathname\"\n *\n * @remarks\n * When using validation, the attached format will be available in your validated body.\n * For array/fields uploads, an array of the specified format will be attached.\n */\n attachToBody?: \"pathname\" | \"url\" | \"file\" | false;\n /**\n * Maximum file size in bytes.\n * Overrides the framework-level default for this uploadDir category.\n *\n * @example\n * maxSize: 1024 * 1024 * 5 // 5MB\n * maxSize: 1024 * 1024 * 50 // 50MB\n */\n maxSize?: number;\n /**\n * Allowed file types/extensions.\n * Can be an array of extensions/MIME types or a RegExp pattern.\n * Overrides the framework-level default for this uploadDir category.\n *\n * @example\n * // Array of extensions\n * allowedFileTypes: [\".jpg\", \".png\", \".gif\"]\n *\n * @example\n * // Array of MIME types\n * allowedFileTypes: [\"image/jpeg\", \"image/png\"]\n *\n * @example\n * // RegExp pattern\n * allowedFileTypes: /jpeg|jpg|png|gif/\n */\n allowedFileTypes?: string[] | RegExp;\n /**\n * Defines if this file field is required\n *\n * @default true\n */\n required?: boolean;\n /**\n * Open API field description\n */\n description?: string;\n};\n"]}
|
|
@@ -7,7 +7,11 @@ import { catchAsync } from "../../../../exports/error-handler/index.js";
|
|
|
7
7
|
import deepmerge from "../../../helpers/deepmerge.helper.js";
|
|
8
8
|
import ExitError from "../../../helpers/exit-error.js";
|
|
9
9
|
import uploadManager from "./upload-manager.js";
|
|
10
|
-
export function applyArkosRouterProxy(target, options,
|
|
10
|
+
export function applyArkosRouterProxy(target, options, component = "router") {
|
|
11
|
+
target._arkos = {
|
|
12
|
+
options,
|
|
13
|
+
routes: [],
|
|
14
|
+
};
|
|
11
15
|
return new Proxy(target, {
|
|
12
16
|
get(target, prop, receiver) {
|
|
13
17
|
const originalMethod = Reflect.get(target, prop, receiver);
|
|
@@ -24,17 +28,20 @@ export function applyArkosRouterProxy(target, options, name = "ArkosRouter()") {
|
|
|
24
28
|
];
|
|
25
29
|
if (prop === "use") {
|
|
26
30
|
return function (config, ...handlers) {
|
|
27
|
-
if (
|
|
31
|
+
if (typeof config === "function" || Array.isArray(config)) {
|
|
32
|
+
handlers = [config, ...handlers];
|
|
33
|
+
config = {};
|
|
34
|
+
}
|
|
35
|
+
else if (!config ||
|
|
28
36
|
typeof config !== "object" ||
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
37
|
+
typeof config === "string" ||
|
|
38
|
+
config instanceof RegExp) {
|
|
39
|
+
throw ExitError(`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}.`);
|
|
40
|
+
}
|
|
32
41
|
if (config.disabled)
|
|
33
42
|
return;
|
|
34
43
|
const useConfig = config;
|
|
35
|
-
const path = useConfig.path
|
|
36
|
-
? applyPrefix(options?.prefix, useConfig.path)
|
|
37
|
-
: undefined;
|
|
44
|
+
const path = applyPrefix(options?.prefix, useConfig.path ?? "/");
|
|
38
45
|
const arkosConfig = getArkosConfig();
|
|
39
46
|
const authenticationConfig = arkosConfig.authentication;
|
|
40
47
|
if (useConfig.authentication && !authenticationConfig?.mode)
|
|
@@ -43,9 +50,7 @@ export function applyArkosRouterProxy(target, options, name = "ArkosRouter()") {
|
|
|
43
50
|
For further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`);
|
|
44
51
|
const middlewareStack = getMiddlewareStack(useConfig);
|
|
45
52
|
const allHandlers = [...middlewareStack, ...handlers];
|
|
46
|
-
return path
|
|
47
|
-
? originalMethod.call(target, path, ...allHandlers)
|
|
48
|
-
: originalMethod.call(target, ...allHandlers);
|
|
53
|
+
return originalMethod.call(target, path, ...allHandlers);
|
|
49
54
|
};
|
|
50
55
|
}
|
|
51
56
|
if (prop === "route") {
|
|
@@ -53,15 +58,10 @@ For further help see https://www.arkosjs.com/docs/core-concepts/authentication/s
|
|
|
53
58
|
const routeChain = {};
|
|
54
59
|
httpMethods.forEach((method) => {
|
|
55
60
|
routeChain[method] = function (config, ...handlers) {
|
|
61
|
+
if (typeof config === "function" || Array.isArray(config))
|
|
62
|
+
throw ExitError(`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}`);
|
|
56
63
|
const fullConfig = {
|
|
57
64
|
...config,
|
|
58
|
-
...(options?.openapi
|
|
59
|
-
? {
|
|
60
|
-
experimental: {
|
|
61
|
-
openapi: options.openapi,
|
|
62
|
-
},
|
|
63
|
-
}
|
|
64
|
-
: {}),
|
|
65
65
|
path,
|
|
66
66
|
};
|
|
67
67
|
receiver[method](fullConfig, ...handlers);
|
|
@@ -73,10 +73,10 @@ For further help see https://www.arkosjs.com/docs/core-concepts/authentication/s
|
|
|
73
73
|
}
|
|
74
74
|
if (httpMethods.includes(prop)) {
|
|
75
75
|
return function (config, ...handlers) {
|
|
76
|
-
if (config.
|
|
76
|
+
if (!config || !RouteConfigValidator.isArkosRouteConfig(config))
|
|
77
|
+
throw ExitError(`First argument of ${component}.${prop}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === "object" ? JSON.stringify(config, null, 2) : config}`);
|
|
78
|
+
if (config?.disabled)
|
|
77
79
|
return;
|
|
78
|
-
if (!RouteConfigValidator.isArkosRouteConfig(config))
|
|
79
|
-
throw Error(`First argument of ${name}.${prop}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === "object" ? JSON.stringify(config, null, 2) : config}`);
|
|
80
80
|
const path = applyPrefix(options?.prefix, config.path);
|
|
81
81
|
config = {
|
|
82
82
|
...config,
|
|
@@ -91,9 +91,9 @@ For further help see https://www.arkosjs.com/docs/core-concepts/authentication/s
|
|
|
91
91
|
path,
|
|
92
92
|
};
|
|
93
93
|
if ([null, undefined].includes(path))
|
|
94
|
-
throw Error("Please pass valid value for path field to use in your route");
|
|
94
|
+
throw new Error("Please pass valid value for path field to use in your route");
|
|
95
95
|
const method = prop;
|
|
96
|
-
const UndefinedHandlerError = (handler) =>
|
|
96
|
+
const UndefinedHandlerError = (handler) => ExitError(`Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`);
|
|
97
97
|
if (handlers.length > 0) {
|
|
98
98
|
const flattenHandlers = (arr) => {
|
|
99
99
|
return arr.reduce((flat, item) => {
|
|
@@ -104,15 +104,19 @@ For further help see https://www.arkosjs.com/docs/core-concepts/authentication/s
|
|
|
104
104
|
handlers = flatHandlers.map((handler) => {
|
|
105
105
|
if (!handler)
|
|
106
106
|
throw UndefinedHandlerError(handler);
|
|
107
|
-
if (typeof handler !== "function")
|
|
107
|
+
if (typeof handler !== "function")
|
|
108
108
|
throw UndefinedHandlerError(handler);
|
|
109
|
-
}
|
|
110
109
|
return catchAsync(handler, {
|
|
111
110
|
type: handler.length > 3 ? "error" : "normal",
|
|
112
111
|
});
|
|
113
112
|
});
|
|
114
113
|
const finalHandler = handlers[handlers.length - 1];
|
|
115
114
|
RouteConfigRegistry.register(finalHandler, config, method);
|
|
115
|
+
target._arkos.routes.push({
|
|
116
|
+
handler: finalHandler,
|
|
117
|
+
config,
|
|
118
|
+
method,
|
|
119
|
+
});
|
|
116
120
|
}
|
|
117
121
|
const arkosConfig = getArkosConfig();
|
|
118
122
|
const validationConfig = arkosConfig.validation;
|
|
@@ -124,15 +128,17 @@ For further help see https://www.arkosjs.com/docs/core-concepts/authentication/s
|
|
|
124
128
|
("validation" in config &&
|
|
125
129
|
!config.validation &&
|
|
126
130
|
config.validation !== undefined)))
|
|
127
|
-
throw
|
|
131
|
+
throw ExitError("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.");
|
|
128
132
|
if (!validationConfig?.resolver &&
|
|
129
133
|
Object.keys(config.validation || {}).length > 0)
|
|
130
|
-
throw
|
|
134
|
+
throw ExitError(`Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`);
|
|
131
135
|
if (config.authentication && !authenticationConfig?.mode)
|
|
132
|
-
throw
|
|
136
|
+
throw ExitError(`Trying to authenticate route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}
|
|
133
137
|
|
|
134
138
|
For further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`);
|
|
135
139
|
handlers = [...getMiddlewareStack(config), ...handlers];
|
|
140
|
+
if (handlers.length === 0)
|
|
141
|
+
throw ExitError(`No handlers provided for route ${method.toUpperCase()} ${path}.`);
|
|
136
142
|
if (config.experimental?.uploads &&
|
|
137
143
|
config.experimental.uploads.deleteOnError !== false)
|
|
138
144
|
handlers.push(catchAsync(uploadManager.handleFileCleanup(config.experimental.uploads), { type: "error" }));
|
|
@@ -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":"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,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,SAAS,MAAM,mCAAmC,CAAC;AAC1D,OAAO,SAAS,MAAM,6BAA6B,CAAC;AACpD,OAAO,aAAa,MAAM,kBAAkB,CAAC;AAE7C,MAAM,UAAU,qBAAqB,CACnC,MAAS,EACT,OAGC,EACD,OAAgC,eAAe;IAE/C,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;gB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gC,KAAK,+DAA+D,oBAAoB,EAAE;;sFAElD,CACzE,CAAC;oBAEJ,QAAQ,GAAG,CAAC,GAAG,kBAAkB,CAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAExD,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 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 name: \"app\" | \"ArkosRouter()\" = \"ArkosRouter()\"\n): T {\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 // if not an ArkosUseConfig object, fall through to native Express use\n if (\n !config ||\n typeof config !== \"object\" ||\n Array.isArray(config) ||\n typeof config === \"function\"\n )\n return originalMethod.call(target, config, ...handlers);\n\n if ((config as ArkosUseConfig).disabled) return;\n\n const useConfig = config as ArkosUseConfig;\n const path = useConfig.path\n ? applyPrefix(options?.prefix, useConfig.path)\n : undefined;\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\n const allHandlers = [...middlewareStack, ...handlers];\n\n return path\n ? originalMethod.call(target, path, ...allHandlers)\n : originalMethod.call(target, ...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 const fullConfig: ArkosRouteConfig = {\n ...config,\n ...(options?.openapi\n ? {\n experimental: {\n openapi: options.openapi,\n },\n }\n : {}),\n path,\n };\n\n receiver[method](fullConfig, ...handlers);\n\n return routeChain as IArkosRoute;\n };\n });\n\n return routeChain;\n };\n }\n\n if (httpMethods.includes(prop as any)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ${name}.${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = {\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 Error(\n \"Please pass valid value for path field to use in your route\"\n );\n\n const method = prop as string;\n const UndefinedHandlerError = (handler: any) =>\n Error(\n `Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`\n );\n\n if (handlers.length > 0) {\n const flattenHandlers = (arr: any[]): ArkosAnyRequestHandler[] => {\n return arr.reduce((flat, item) => {\n return flat.concat(\n Array.isArray(item) ? flattenHandlers(item) : item\n );\n }, []);\n };\n\n const flatHandlers = flattenHandlers(handlers);\n\n handlers = flatHandlers.map((handler: ArkosAnyRequestHandler) => {\n if (!handler) throw UndefinedHandlerError(handler);\n\n if (typeof handler !== \"function\") {\n throw UndefinedHandlerError(handler);\n }\n\n return catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n });\n });\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n const route = `${method.toUpperCase()} ${path}`;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (\n !validationConfig?.resolver &&\n Object.keys(config.validation || {}).length > 0\n )\n throw Error(\n `Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n `Trying to authenticate route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n });\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":"AASA,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,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,SAAS,MAAM,mCAAmC,CAAC;AAC1D,OAAO,SAAS,MAAM,6BAA6B,CAAC;AACpD,OAAO,aAAa,MAAM,kBAAkB,CAAC;AAE7C,MAAM,UAAU,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,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B,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"]}
|
|
@@ -10,22 +10,23 @@ import multer from "multer";
|
|
|
10
10
|
import { catchAsync } from "../../../../exports/error-handler/index.js";
|
|
11
11
|
export function extractArkosRoutes(app, basePath = "") {
|
|
12
12
|
const routes = [];
|
|
13
|
-
function extractFromStack(stack, prefix = "") {
|
|
13
|
+
function extractFromStack(stack, prefix = "", inheritedRouteOptions) {
|
|
14
|
+
if (Object.keys(inheritedRouteOptions || {}).length === 0)
|
|
15
|
+
inheritedRouteOptions = undefined;
|
|
14
16
|
stack.forEach((layer) => {
|
|
15
17
|
if (layer.route) {
|
|
16
18
|
const fullPath = prefix + layer.route.path;
|
|
17
19
|
const methods = Object.keys(layer.route.methods);
|
|
18
20
|
methods.forEach((method) => {
|
|
19
21
|
const handlers = layer.route.stack || [];
|
|
20
|
-
let config;
|
|
21
22
|
for (const handler of handlers) {
|
|
22
23
|
const foundConfig = RouteConfigRegistry.get(handler.handle);
|
|
23
24
|
if (foundConfig) {
|
|
24
|
-
config = foundConfig;
|
|
25
25
|
routes.push({
|
|
26
26
|
path: fullPath,
|
|
27
27
|
method: method.toUpperCase(),
|
|
28
|
-
config,
|
|
28
|
+
config: foundConfig,
|
|
29
|
+
routeOptions: inheritedRouteOptions,
|
|
29
30
|
});
|
|
30
31
|
break;
|
|
31
32
|
}
|
|
@@ -45,13 +46,15 @@ export function extractArkosRoutes(app, basePath = "") {
|
|
|
45
46
|
.replace(/\/$/, "");
|
|
46
47
|
}
|
|
47
48
|
}
|
|
48
|
-
extractFromStack(layer.handle.stack, nestedPrefix
|
|
49
|
+
extractFromStack(layer.handle.stack, nestedPrefix, layer.handle._arkos?.options?.openapi
|
|
50
|
+
? layer.handle._arkos.options
|
|
51
|
+
: inheritedRouteOptions);
|
|
49
52
|
}
|
|
50
53
|
});
|
|
51
54
|
}
|
|
52
55
|
const stack = app._router?.stack || app.stack;
|
|
53
56
|
if (stack)
|
|
54
|
-
extractFromStack(stack, basePath);
|
|
57
|
+
extractFromStack(stack, basePath, app._arkos?.options || undefined);
|
|
55
58
|
return routes;
|
|
56
59
|
}
|
|
57
60
|
export function getMiddlewareStack(config) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,oBAAoB,CAAC;AAC3C,OAAO,WAAW,MAAM,uCAAuC,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,mBAAmB,MAAM,6BAA6B,CAAC;AAE9D,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,uCAAuC,CAAC;AACpE,OAAO,aAAa,MAAM,kBAAkB,CAAC;AAC7C,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAE/D,MAAM,UAAU,kBAAkB,CAChC,GAAQ,EACR,QAAQ,GAAG,EAAE;IAMb,MAAM,MAAM,GAIP,EAAE,CAAC;IAER,SAAS,gBAAgB,CAAC,KAAY,EAAE,MAAM,GAAG,EAAE;QACjD,KAAK,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,EAAE;YAC3B,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;gBAChB,MAAM,QAAQ,GAAG,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC;gBAC3C,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK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Limit from \"express-rate-limit\";\nimport authService from \"../../../../modules/auth/auth.service\";\nimport { validateRequestInputs } from \"../../../../modules/base/base.middlewares\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { ArkosRouteConfig } from \"../../types\";\nimport express from \"express\";\nimport compression from \"compression\";\nimport { queryParser } from \"../../../helpers/query-parser.helpers\";\nimport uploadManager from \"./upload-manager\";\nimport multer from \"multer\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\n\nexport function extractArkosRoutes(\n app: any,\n basePath = \"\"\n): Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n}> {\n const routes: Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n }> = [];\n\n function extractFromStack(stack: any[], prefix = \"\") {\n stack.forEach((layer: any) => {\n if (layer.route) {\n const fullPath = prefix + layer.route.path;\n const methods = Object.keys(layer.route.methods);\n\n methods.forEach((method) => {\n const handlers = layer.route.stack || [];\n let config: ArkosRouteConfig | undefined;\n\n for (const handler of handlers) {\n const foundConfig = RouteConfigRegistry.get(handler.handle);\n\n if (foundConfig) {\n config = foundConfig;\n routes.push({\n path: fullPath,\n method: method.toUpperCase(),\n config,\n });\n\n break;\n }\n }\n });\n } else if (layer.name === \"router\" && layer.handle?.stack) {\n let nestedPrefix = prefix;\n\n if (layer.regexp) {\n const match = layer.regexp\n .toString()\n .match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (match) {\n nestedPrefix = prefix + \"/\" + match[1].replace(/\\\\\\//g, \"/\");\n nestedPrefix = nestedPrefix\n .replace(/\\/\\//g, \"/\")\n .replace(/\\/$/, \"\");\n }\n }\n\n extractFromStack(layer.handle.stack, nestedPrefix);\n }\n });\n }\n\n const stack = app._router?.stack || app.stack;\n if (stack) extractFromStack(stack, basePath);\n\n return routes;\n}\n\nexport function getMiddlewareStack(\n config: ArkosRouteConfig | Omit<ArkosRouteConfig, \"path\">\n) {\n const middlewares = [];\n\n if (config.authentication) middlewares.push(authService.authenticate);\n\n if (\n typeof config.authentication === \"object\" &&\n config.authentication.action &&\n config.authentication.resource\n )\n middlewares.push(\n authService.authorize(\n config.authentication.action,\n config.authentication.resource,\n config.authentication?.rule\n )\n );\n\n if (config.rateLimit) middlewares.push(rateLimit(config.rateLimit));\n if (config.compression) middlewares.push(compression(config.compression));\n if (config.queryParser) middlewares.push(queryParser(config.queryParser));\n\n if (config?.bodyParser) {\n const parsers = Array.isArray(config.bodyParser)\n ? config.bodyParser\n : [config.bodyParser];\n\n parsers.forEach((parser) => {\n if (typeof parser === \"object\" && parser.parser)\n if (parser.parser !== \"multipart\")\n middlewares.push(catchAsync(express[parser.parser](parser.options)));\n else if (parser.parser === \"multipart\")\n middlewares.push(\n catchAsync(multer({ limits: parser.options }).none())\n );\n });\n }\n\n if (config.experimental?.uploads) {\n const uploadConfig = config.experimental.uploads;\n middlewares.push(uploadManager.handleUpload(uploadConfig));\n middlewares.push(uploadManager.validateRequiredFiles(uploadConfig));\n\n middlewares.push(validateRequestInputs(config as ArkosRouteConfig));\n\n middlewares.push(\n uploadManager.handlePostUpload(config.experimental.uploads)\n );\n } else middlewares.push(validateRequestInputs(config as ArkosRouteConfig));\n\n return middlewares;\n}\n\n/**\n * Extracts path parameters from an Express route path\n *\n * @param path - Express route path with :param syntax\n * @returns Array of parameter names\n *\n * @example\n * extractPathParams('/api/users/:userId/posts/:postId')\n * // => ['userId', 'postId']\n *\n */\nexport function extractPathParams(path: string): string[] {\n const params: string[] = [];\n const segments = path.split(\"/\");\n let wildcardCount = 0;\n\n for (const segment of segments) {\n if (segment === \"*\") {\n wildcardCount++;\n } else if (segment.startsWith(\":\")) {\n const clean = segment.substring(1).replace(/\\(.*\\)$/, \"\");\n params.push(clean);\n }\n }\n\n if (wildcardCount === 1) {\n params.push(\"path\");\n } else {\n for (let i = 1; i <= wildcardCount; i++) {\n params.push(`path${i}`);\n }\n }\n\n return params;\n}\n\ntype PathLike = string | RegExp;\ntype PathInput = PathLike | PathLike[];\n\nexport function applyPrefix(\n prefix: PathInput = \"\",\n path: PathInput\n): PathInput {\n if (!prefix) return path;\n\n const prefixArr = Array.isArray(prefix) ? prefix : [prefix];\n const pathArr = Array.isArray(path) ? path : [path];\n\n const result: PathLike[] = [];\n\n for (const pfx of prefixArr) {\n for (const pth of pathArr) {\n result.push(applySinglePrefix(pfx, pth));\n }\n }\n\n return result.length === 1 ? result[0] : result;\n}\n\nfunction applySinglePrefix(prefix: PathLike, path: PathLike): PathLike {\n const isPrefixRegex = prefix instanceof RegExp;\n const isPathRegex = path instanceof RegExp;\n\n if (typeof prefix === \"string\" && typeof path === \"string\") {\n const normalizedPrefix = prefix.endsWith(\"/\")\n ? prefix.slice(0, -1)\n : prefix;\n\n return `${normalizedPrefix}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n\n if (typeof prefix === \"string\" && isPathRegex) {\n const escapedPrefix = prefix\n .replace(/\\/$/, \"\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n const source = path.source.startsWith(\"^\")\n ? path.source.slice(1)\n : path.source;\n\n return new RegExp(`^${escapedPrefix}${source}`, path.flags);\n }\n\n if (isPrefixRegex && typeof path === \"string\") {\n const escapedPath = path.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n const prefixSource = prefix.source.endsWith(\"$\")\n ? prefix.source.slice(0, -1)\n : prefix.source;\n\n return new RegExp(`^${prefixSource}${escapedPath}`, prefix.flags);\n }\n\n if (isPrefixRegex && isPathRegex) {\n const prefixSource = prefix.source.endsWith(\"$\")\n ? prefix.source.slice(0, -1)\n : prefix.source;\n\n const pathSource = path.source.startsWith(\"^\")\n ? path.source.slice(1)\n : path.source;\n\n const flags = Array.from(new Set([...prefix.flags, ...path.flags])).join(\n \"\"\n );\n\n return new RegExp(`^${prefixSource}${pathSource}`, flags);\n }\n\n throw new TypeError(\"Invalid prefix or path\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../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nimport { validateRequestInputs } from \"../../../../modules/base/base.middlewares\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { ArkosRouteConfig } from \"../../types\";\nimport express from \"express\";\nimport compression from \"compression\";\nimport { queryParser } from \"../../../helpers/query-parser.helpers\";\nimport uploadManager from \"./upload-manager\";\nimport multer from \"multer\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\nimport { ArkosRouterOptions } from \"../..\";\n\nexport function extractArkosRoutes(\n app: any,\n basePath = \"\"\n): Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n routeOptions?: ArkosRouterOptions;\n}> {\n const routes: Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n routeOptions?: ArkosRouterOptions;\n }> = [];\n\n function extractFromStack(\n stack: any[],\n prefix = \"\",\n inheritedRouteOptions?: ArkosRouterOptions\n ) {\n if (Object.keys(inheritedRouteOptions || {}).length === 0)\n inheritedRouteOptions = undefined;\n\n stack.forEach((layer: any) => {\n if (layer.route) {\n const fullPath = prefix + layer.route.path;\n const methods = Object.keys(layer.route.methods);\n\n methods.forEach((method) => {\n const handlers = layer.route.stack || [];\n\n for (const handler of handlers) {\n const foundConfig = RouteConfigRegistry.get(handler.handle);\n\n if (foundConfig) {\n routes.push({\n path: fullPath,\n method: method.toUpperCase(),\n config: foundConfig,\n routeOptions: inheritedRouteOptions,\n });\n\n break;\n }\n }\n });\n } else if (layer.name === \"router\" && layer.handle?.stack) {\n let nestedPrefix = prefix;\n\n if (layer.regexp) {\n const match = layer.regexp\n .toString()\n .match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (match) {\n nestedPrefix = prefix + \"/\" + match[1].replace(/\\\\\\//g, \"/\");\n nestedPrefix = nestedPrefix\n .replace(/\\/\\//g, \"/\")\n .replace(/\\/$/, \"\");\n }\n }\n\n extractFromStack(\n layer.handle.stack,\n nestedPrefix,\n layer.handle._arkos?.options?.openapi\n ? layer.handle._arkos.options\n : inheritedRouteOptions\n );\n }\n });\n }\n\n const stack = app._router?.stack || app.stack;\n if (stack)\n extractFromStack(stack, basePath, app._arkos?.options || undefined);\n\n return routes;\n}\n\nexport function getMiddlewareStack(\n config: ArkosRouteConfig | Omit<ArkosRouteConfig, \"path\">\n) {\n const middlewares = [];\n\n if (config.authentication) middlewares.push(authService.authenticate);\n\n if (\n typeof config.authentication === \"object\" &&\n config.authentication.action &&\n config.authentication.resource\n )\n middlewares.push(\n authService.authorize(\n config.authentication.action,\n config.authentication.resource,\n config.authentication?.rule\n )\n );\n\n if (config.rateLimit) middlewares.push(rateLimit(config.rateLimit));\n if (config.compression) middlewares.push(compression(config.compression));\n if (config.queryParser) middlewares.push(queryParser(config.queryParser));\n\n if (config?.bodyParser) {\n const parsers = Array.isArray(config.bodyParser)\n ? config.bodyParser\n : [config.bodyParser];\n\n parsers.forEach((parser) => {\n if (typeof parser === \"object\" && parser.parser)\n if (parser.parser !== \"multipart\")\n middlewares.push(catchAsync(express[parser.parser](parser.options)));\n else if (parser.parser === \"multipart\")\n middlewares.push(\n catchAsync(multer({ limits: parser.options }).none())\n );\n });\n }\n\n if (config.experimental?.uploads) {\n const uploadConfig = config.experimental.uploads;\n middlewares.push(uploadManager.handleUpload(uploadConfig));\n middlewares.push(uploadManager.validateRequiredFiles(uploadConfig));\n\n middlewares.push(validateRequestInputs(config as ArkosRouteConfig));\n\n middlewares.push(\n uploadManager.handlePostUpload(config.experimental.uploads)\n );\n } else middlewares.push(validateRequestInputs(config as ArkosRouteConfig));\n\n return middlewares;\n}\n\n/**\n * Extracts path parameters from an Express route path\n *\n * @param path - Express route path with :param syntax\n * @returns Array of parameter names\n *\n * @example\n * extractPathParams('/api/users/:userId/posts/:postId')\n * // => ['userId', 'postId']\n *\n */\nexport function extractPathParams(path: string): string[] {\n const params: string[] = [];\n const segments = path.split(\"/\");\n let wildcardCount = 0;\n\n for (const segment of segments) {\n if (segment === \"*\") {\n wildcardCount++;\n } else if (segment.startsWith(\":\")) {\n const clean = segment.substring(1).replace(/\\(.*\\)$/, \"\");\n params.push(clean);\n }\n }\n\n if (wildcardCount === 1) {\n params.push(\"path\");\n } else {\n for (let i = 1; i <= wildcardCount; i++) {\n params.push(`path${i}`);\n }\n }\n\n return params;\n}\n\ntype PathLike = string | RegExp;\ntype PathInput = PathLike | PathLike[];\n\nexport function applyPrefix(\n prefix: PathInput = \"\",\n path: PathInput\n): PathInput {\n if (!prefix) return path;\n\n const prefixArr = Array.isArray(prefix) ? prefix : [prefix];\n const pathArr = Array.isArray(path) ? path : [path];\n\n const result: PathLike[] = [];\n\n for (const pfx of prefixArr) {\n for (const pth of pathArr) {\n result.push(applySinglePrefix(pfx, pth));\n }\n }\n\n return result.length === 1 ? result[0] : result;\n}\n\nfunction applySinglePrefix(prefix: PathLike, path: PathLike): PathLike {\n const isPrefixRegex = prefix instanceof RegExp;\n const isPathRegex = path instanceof RegExp;\n\n if (typeof prefix === \"string\" && typeof path === \"string\") {\n const normalizedPrefix = prefix.endsWith(\"/\")\n ? prefix.slice(0, -1)\n : prefix;\n\n return `${normalizedPrefix}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n\n if (typeof prefix === \"string\" && isPathRegex) {\n const escapedPrefix = prefix\n .replace(/\\/$/, \"\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n const source = path.source.startsWith(\"^\")\n ? path.source.slice(1)\n : path.source;\n\n return new RegExp(`^${escapedPrefix}${source}`, path.flags);\n }\n\n if (isPrefixRegex && typeof path === \"string\") {\n const escapedPath = path.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n const prefixSource = prefix.source.endsWith(\"$\")\n ? prefix.source.slice(0, -1)\n : prefix.source;\n\n return new RegExp(`^${prefixSource}${escapedPath}`, prefix.flags);\n }\n\n if (isPrefixRegex && isPathRegex) {\n const prefixSource = prefix.source.endsWith(\"$\")\n ? prefix.source.slice(0, -1)\n : prefix.source;\n\n const pathSource = path.source.startsWith(\"^\")\n ? path.source.slice(1)\n : path.source;\n\n const flags = Array.from(new Set([...prefix.flags, ...path.flags])).join(\n \"\"\n );\n\n return new RegExp(`^${prefixSource}${pathSource}`, flags);\n }\n\n throw new TypeError(\"Invalid prefix or path\");\n}\n"]}
|