arkos 1.4.1-canary.8 → 1.5.0-canary.1

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.
Files changed (118) hide show
  1. package/dist/cjs/modules/auth/auth.controller.js +13 -0
  2. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  3. package/dist/cjs/modules/auth/auth.service.js +40 -14
  4. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  5. package/dist/cjs/modules/auth/utils/services/auth-action.service.js +1 -1
  6. package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
  7. package/dist/cjs/modules/base/base.middlewares.js +6 -4
  8. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  9. package/dist/cjs/modules/base/utils/error-prettifier.js +185 -0
  10. package/dist/cjs/modules/base/utils/error-prettifier.js.map +1 -0
  11. package/dist/cjs/modules/email/email.service.js +4 -1
  12. package/dist/cjs/modules/email/email.service.js.map +1 -1
  13. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  14. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +9 -3
  15. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  16. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  17. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  18. package/dist/cjs/types/auth.js.map +1 -1
  19. package/dist/cjs/utils/arkos-router/index.js +7 -1
  20. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  21. package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
  22. package/dist/cjs/utils/arkos-router/utils/helpers/index.js +51 -0
  23. package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
  24. package/dist/cjs/utils/cli/generate.js +38 -0
  25. package/dist/cjs/utils/cli/generate.js.map +1 -1
  26. package/dist/cjs/utils/cli/index.js +37 -4
  27. package/dist/cjs/utils/cli/index.js.map +1 -1
  28. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  29. package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
  30. package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
  31. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +556 -0
  32. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
  33. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +327 -0
  34. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
  35. package/dist/cjs/utils/cli/utils/template-generators.js +14 -8
  36. package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
  37. package/dist/cjs/utils/dynamic-loader.js +2 -2
  38. package/dist/cjs/utils/dynamic-loader.js.map +1 -1
  39. package/dist/cjs/utils/helpers/routers.helpers.js +2 -3
  40. package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
  41. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +5 -5
  42. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  43. package/dist/esm/modules/auth/auth.controller.js +13 -0
  44. package/dist/esm/modules/auth/auth.controller.js.map +1 -1
  45. package/dist/esm/modules/auth/auth.service.js +40 -14
  46. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  47. package/dist/esm/modules/auth/utils/services/auth-action.service.js +1 -1
  48. package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
  49. package/dist/esm/modules/base/base.middlewares.js +6 -4
  50. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  51. package/dist/esm/modules/base/utils/error-prettifier.js +181 -0
  52. package/dist/esm/modules/base/utils/error-prettifier.js.map +1 -0
  53. package/dist/esm/modules/email/email.service.js +4 -1
  54. package/dist/esm/modules/email/email.service.js.map +1 -1
  55. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  56. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +9 -3
  57. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  58. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  59. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  60. package/dist/esm/types/auth.js.map +1 -1
  61. package/dist/esm/utils/arkos-router/index.js +8 -2
  62. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  63. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  64. package/dist/esm/utils/arkos-router/utils/helpers/index.js +50 -0
  65. package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
  66. package/dist/esm/utils/cli/generate.js +38 -0
  67. package/dist/esm/utils/cli/generate.js.map +1 -1
  68. package/dist/esm/utils/cli/index.js +37 -4
  69. package/dist/esm/utils/cli/index.js.map +1 -1
  70. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  71. package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
  72. package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
  73. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +549 -0
  74. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
  75. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +320 -0
  76. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
  77. package/dist/esm/utils/cli/utils/template-generators.js +14 -8
  78. package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
  79. package/dist/esm/utils/dynamic-loader.js +2 -2
  80. package/dist/esm/utils/dynamic-loader.js.map +1 -1
  81. package/dist/esm/utils/helpers/routers.helpers.js +2 -3
  82. package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
  83. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +5 -5
  84. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  85. package/dist/types/modules/auth/auth.service.d.ts +5 -0
  86. package/dist/types/modules/auth/utils/services/auth-action.service.d.ts +1 -1
  87. package/dist/types/modules/base/utils/error-prettifier.d.ts +19 -0
  88. package/dist/types/modules/email/email.service.d.ts +4 -8
  89. package/dist/types/types/auth.d.ts +3 -3
  90. package/dist/types/utils/arkos-router/index.d.ts +3 -1
  91. package/dist/types/utils/arkos-router/types/index.d.ts +2 -2
  92. package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +4 -0
  93. package/dist/types/utils/cli/generate.d.ts +4 -0
  94. package/dist/types/utils/cli/utils/template-generator/templates/auth-configs-template.d.ts +3 -1
  95. package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +18 -0
  96. package/dist/types/utils/cli/utils/template-generator/templates/zod-schema-generator.d.ts +14 -0
  97. package/dist/types/utils/helpers/routers.helpers.d.ts +1 -1
  98. package/package.json +1 -1
  99. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -187
  100. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
  101. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -181
  102. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
  103. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -106
  104. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
  105. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -104
  106. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
  107. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -181
  108. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
  109. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -175
  110. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
  111. package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -100
  112. package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
  113. package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -98
  114. package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
  115. package/dist/types/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.d.ts +0 -2
  116. package/dist/types/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.d.ts +0 -2
  117. package/dist/types/utils/cli/utils/template-generator/templates/zod/create-schema-template.d.ts +0 -2
  118. package/dist/types/utils/cli/utils/template-generator/templates/zod/update-schema-template.d.ts +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":"AAAA,OAAO,UAA2B,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AAqCxD,MAAM,OAAO,YAAY;IAUvB,YAAY,MAA8B;QATlC,gBAAW,GAAuB,IAAI,CAAC;QACvC,iBAAY,GAAiC,IAAI,CAAC;QASxD,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC7B,CAAC;IACH,CAAC;IAUO,cAAc;QACpB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,YAAY,CAAC;QAC3B,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,cAAc,EAAE,CAAC;QACjD,MAAM,IAAI,GAAG,YAAY,EAAE,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;QAC1D,MAAM,IAAI,G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AAgB,CAC3B,mBAAiC;QAEjC,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,mBAAmB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACjE,MAAM,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,eAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n from?: string;\n to: string | string[];\n subject: string;\n text?: string;\n html: string;\n};\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n private transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text: options?.text || convert(options.html),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
1
+ {"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.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,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,eAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI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I,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,gDAAgD;gBACzD,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,EAAE;aACT,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,SAAS;SAChB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message:\n err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE5D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IACnD,IAAI,GAAG,CAAC,I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AC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message:\n err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -1,3 +1,4 @@
1
+ import { pascalCase } from "../../../utils/features/change-case.features.js";
1
2
  import AppError from "./app-error.js";
2
3
  export function handleJWTError() {
3
4
  return new AppError("Invalid token. Please log in again!", 401);
@@ -41,7 +42,9 @@ export function handleRecordNotFoundError(_) {
41
42
  export function handleUniqueConstraintError(err) {
42
43
  const field = err?.meta?.target || "unknown field";
43
44
  const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;
44
- return new AppError(message, 409);
45
+ return new AppError(message, 409, (err.meta?.modelName &&
46
+ `${pascalCase(err.meta?.modelName)}${pascalCase(err.meta?.target?.[0])}UniqueConstraint`) ||
47
+ "Unknown");
45
48
  }
46
49
  export function handleForeignKeyConstraintError(_) {
47
50
  const message = "Foreign key constraint violation. Ensure that the referenced record exists.";
@@ -155,9 +158,12 @@ export function handleEmptyResultError(_) {
155
158
  export function handleNonExistingRecord(err) {
156
159
  const message = err?.meta?.cause ||
157
160
  `Operation could not be completed as the required record was not found`;
158
- return new AppError(message, 404, err.meta || {}, "RecordNotFound");
161
+ const model = err?.meta?.cause
162
+ ? err?.meta?.cause?.split("No '")?.[1]?.split?.("'")?.[0]
163
+ : "";
164
+ return new AppError(message, 404, `Inline${pascalCase(model || "")}RecordNotFound`);
159
165
  }
160
166
  export function handlePrismaClientInitializationError(_) {
161
- return new AppError("Service temporarily unavailable", 503, {}, "DatabaseNotAvailable");
167
+ return new AppError("Service temporarily unavailable", 503, "DatabaseNotAvailable");
162
168
  }
163
169
  //# sourceMappingURL=error-handler.helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,aAAa,CAAC;AASnC,MAAM,UAAU,cAAc;IAC5B,OAAO,IAAI,QAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,OAAO,IAAI,QAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,GACX,GAAG,EAAE,OAA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C;AACpC,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,CAAW;IAChD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,GAGvC;IACC,MAAM,OAAO,GACX,GAAG,EAAE,IAAI,EAAE,KAAK;QAChB,uEAAuE,CAAC;IAC1E,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,gBAAgB,CAAC,CAAC;AACtE,CAAC;AAED,MAAM,UAAU,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,QAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,EAAE,EACF,sBAAsB,CACvB,CAAC;AACJ,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string;\n message: string;\n meta?: Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message?.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"RecordNotFound\");\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
1
+ {"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,8CAA8C,CAAC;AAC1E,OAAO,QAAQ,MAAM,aAAa,CAAC;AASnC,MAAM,UAAU,cAAc;IAC5B,OAAO,IAAI,QAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,OAAO,IAAI,QAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CA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B,CAAC,GAAa;IAC/C,MAAM,KAAK,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,eAAe,CAAC;IAClD,MAAM,YAAY,GAAG,GAAG,EAAE,IAAI,EAAE,aAAa,IAAI,cAAc,CAAC;IAChE,MAAM,OAAO,GAAG,gCAAgC,KAAK,qBAAqB,YAAY,GAAG,CAAC;IAC1F,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,CAAW;IAChD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,GAGvC;IACC,MAAM,OAAO,GACX,GAAG,EAAE,IAAI,EAAE,KAAK;QAChB,uEAAuE,CAAC;IAE1E,MAAM,KAAK,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK;QAC5B,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;QACzD,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,IAAI,QAAQ,CACjB,OAAO,EACP,GAAG,EACH,SAAS,UAAU,CAAC,KAAK,IAAI,EAAE,CAAC,gBAAgB,CACjD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,QAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,sBAAsB,CACvB,CAAC;AACJ,CAAC","sourcesContent":["import { pascalCase } from \"../../../utils/features/change-case.features\";\nimport AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string;\n message: string;\n meta?: Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message?.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(\n message,\n 409,\n (err.meta?.modelName &&\n `${pascalCase(err.meta?.modelName)}${pascalCase(err.meta?.target?.[0])}UniqueConstraint`) ||\n \"Unknown\"\n );\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n\n const model = err?.meta?.cause\n ? err?.meta?.cause?.split(\"No '\")?.[1]?.split?.(\"'\")?.[0]\n : \"\";\n\n return new AppError(\n message,\n 404,\n `Inline${pascalCase(model || \"\")}RecordNotFound`\n );\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n \"DatabaseNotAvailable\"\n );\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import PrismaJsonSchemaGenerator from "../../../../utils/prisma/prisma-json-schema-generator.js";
2
2
  import pluralize from "pluralize";
3
+ import sheu from "../../../../utils/sheu.js";
3
4
  class MissingJsonSchemasGenerator {
4
5
  extractModelNameFromSchemaRef(schemaRef) {
5
6
  const match = schemaRef.match(/#\/components\/schemas\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/);
@@ -172,6 +173,8 @@ class MissingJsonSchemasGenerator {
172
173
  });
173
174
  }
174
175
  catch (error) {
176
+ sheu.error(`Failed to generate schemas for model ${modelName}`);
177
+ throw error;
175
178
  }
176
179
  }
177
180
  return missingSchemas;
@@ -1 +1 @@
1
- {"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":"AAEA,OAAO,yBAAyB,MAAM,uDAAuD,CAAC;AAC9F,OAAO,SAAS,MAAM,WAAW,CAAC;AAKlC,MAAM,2BAA2B;IAOvB,6BAA6B,CAAC,SAAiB;QACrD,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAC3B,+GAA+G,CAChH,CAAC;QACF,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEzB,IACE,S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I,CAAC,cAAc,CAAC,CAAC;YACpC,CAAC;iBAAM,CAAC;gBACN,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;gBAEjC,IAAI,SAAS,GAAkB,IAAI,CAAC;gBACpC,IAAI,MAAM,GAAkB,IAAI,CAAC;gBAGjC,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;oBACxB,SAAS,GAAG,IAAI,CAAC,+BAA+B,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;oBACtE,MAAM,GAAG,IAAI,CAAC,4BAA4B,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;gBAClE,CAAC;gBAGD,IAAI,CAAC,SAAS,IAAI,CAAC,MAAM,EAAE,CAAC;oBAC1B,SAAS,GAAG,SAAS,IAAI,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjE,MAAM,GAAG,MAAM,IAAI,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC,CAAC;gBAC1D,CAAC;gBAED,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;oBACxB,YAAY,CAAC,IAAI,CAAC;wBAChB,KAAK,EAAE,SAAS;wBAChB,MAAM;wBACN,GAAG;wBACH,WAAW,EAAE,OAAO,CAAC,WAAW;qBACjC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO;YACL,OAAO;YACP,WAAW;YACX,YAAY;YACZ,YAAY;SACb,CAAC;IACJ,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAErE,eAAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport PrismaJsonSchemaGenerator from \"../../../../utils/prisma/prisma-json-schema-generator\";\nimport pluralize from \"pluralize\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName.toLowerCase() === \"auth\" ||\n modelName.toLowerCase() === \"login\" ||\n modelName.toLowerCase() === \"signup\" ||\n modelName.toLowerCase() === \"getme\" ||\n modelName.toLowerCase() === \"updateme\" ||\n modelName.toLowerCase() === \"updatepassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n if (operationId.includes(\"updateMe\")) return \"updateMe\";\n if (operationId.includes(\"updatePassword\")) return \"updatePassword\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\");\n\n // Handle auth operations\n if (\n operationId.toLowerCase().includes(\"login\") ||\n operationId.toLowerCase().includes(\"signup\") ||\n operationId.toLowerCase().includes(\"getme\") ||\n operationId.toLowerCase().includes(\"updateme\") ||\n operationId.toLowerCase().includes(\"updatepassword\")\n ) {\n return \"Auth\";\n }\n\n return pluralize.singular(modelName) || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n /**\n * When using swagger with strict set to false and needs fallback to prisma for the required json schemas that where not manually provided through zod schemas or class validator classes.\n */\n generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Record<string, any> {\n const missingSchemas: Record<string, any> = {};\n\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) continue;\n\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas = PrismaJsonSchemaGenerator.generateModelSchemas(\n {\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n }\n );\n\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n if (key.includes(\"ModelSchema\")) mappedKey = key;\n else mappedKey = `${key}ModelSchema`;\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
1
+ {"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":"AAEA,OAAO,yBAAyB,MAAM,uDAAuD,CAAC;AAC9F,OAAO,SAAS,MAAM,WAAW,C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C;IACJ,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAErE,eAAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport PrismaJsonSchemaGenerator from \"../../../../utils/prisma/prisma-json-schema-generator\";\nimport pluralize from \"pluralize\";\nimport sheu from \"../../../../utils/sheu\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName.toLowerCase() === \"auth\" ||\n modelName.toLowerCase() === \"login\" ||\n modelName.toLowerCase() === \"signup\" ||\n modelName.toLowerCase() === \"getme\" ||\n modelName.toLowerCase() === \"updateme\" ||\n modelName.toLowerCase() === \"updatepassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n if (operationId.includes(\"updateMe\")) return \"updateMe\";\n if (operationId.includes(\"updatePassword\")) return \"updatePassword\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\");\n\n // Handle auth operations\n if (\n operationId.toLowerCase().includes(\"login\") ||\n operationId.toLowerCase().includes(\"signup\") ||\n operationId.toLowerCase().includes(\"getme\") ||\n operationId.toLowerCase().includes(\"updateme\") ||\n operationId.toLowerCase().includes(\"updatepassword\")\n ) {\n return \"Auth\";\n }\n\n return pluralize.singular(modelName) || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n /**\n * When using swagger with strict set to false and needs fallback to prisma for the required json schemas that where not manually provided through zod schemas or class validator classes.\n */\n generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Record<string, any> {\n const missingSchemas: Record<string, any> = {};\n\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) continue;\n\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas = PrismaJsonSchemaGenerator.generateModelSchemas(\n {\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n }\n );\n\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n if (key.includes(\"ModelSchema\")) mappedKey = key;\n else mappedKey = `${key}ModelSchema`;\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n sheu.error(`Failed to generate schemas for model ${modelName}`);\n throw error;\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Base set of controller actions available to all controllers.\n *\n * @example\n * const action: AccessAction = \"Create\";\n * const customAction: AccessAction = \"export\"; // Custom action\n */\nexport type AccessAction = \"Create\" | \"Update\" | \"Delete\" | \"View\" | string;\n\nexport type DetailedAccessControlRule = {\n /** Array of role names that have permission for this action */\n roles?: string[];\n /** Human-readable name for this permission (optional) */\n name?: string;\n /** Detailed description of what this permission allows (optional) */\n description?: string;\n /** Detailed error message of what must be returned on forbidden response (optional)\n *\n * Note: not yet implemented\n * */\n errorMessage?: string;\n};\n\n/**\n * Rules defining access control for different controller actions.\n * The array contains role names that are allowed to perform the action.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n *\n * const rules: AccessControlRules = {\n * Create: {\n * roles: [\"Admin\", \"Manager\"],\n * name: \"Create a new user\",\n * description: \"Allows to create a new user\"\n * },\n * Update: [\"Admin\"],\n * Delete: [\"Admin\"],\n * View: [\"Admin\", \"User\", \"Guest\"]\n * };\n *\n */\nexport type AccessControlRules = {\n [key in AccessAction]: string[] | DetailedAccessControlRule;\n};\n\n/**\n * Rules defining authentication requirements for different controller actions.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * const authRules: AuthenticationControlRules = {\n * Create: true,\n * Update: true,\n * Delete: true,\n * View: false // Public access\n * };\n */\nexport type AuthenticationControlRules = {\n [key in AccessAction]: boolean;\n};\n\n/**\n * Configuration for authentication control.\n *\n * @example\n * // All actions require authentication\n * const config1: AuthenticationControlConfig = true;\n *\n * // Specific rules per action\n * const config2: AuthenticationControlConfig = {\n * Create: true,\n * View: false\n * };\n */\nexport type AuthenticationControlConfig =\n | boolean\n | Partial<AuthenticationControlRules>;\n\n/**\n * Configuration for access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#auth-config-files---static-rbac}\n * @example\n * // All actions allowed for these roles\n * const config1: AccessControlConfig = [\"Admin\", \"Manager\"];\n *\n * // Specific rules per action\n * const config2: AccessControlConfig = {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * };\n */\nexport type AccessControlConfig = string[] | Partial<AccessControlRules>;\n\n/**\n * Configuration for authentication and access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * export const authConfig: AuthConfigs = {\n * authenticationControl: {\n * Create: true,\n * View: false\n * },\n * accessControl: {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * }\n * };\n */\nexport type AuthConfigs = {\n authenticationControl?: AuthenticationControlConfig;\n accessControl?: AccessControlConfig;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n *\n * @example\n * const payload: AuthJwtPayload = {\n * id: 123,\n * roles: [\"Admin\"],\n * email: \"user@example.com\"\n * };\n */\nexport interface AuthJwtPayload extends JwtPayload {\n id?: number | string;\n [x: string]: any;\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Base set of controller actions available to all controllers.\n *\n * @example\n * const action: AccessAction = \"Create\";\n * const customAction: AccessAction = \"export\"; // Custom action\n */\nexport type AccessAction = \"Create\" | \"Update\" | \"Delete\" | \"View\" | string;\n\nexport type DetailedAccessControlRule = {\n /** Array of role names that have permission for this action */\n roles?: string[] | \"*\";\n /** Human-readable name for this permission (optional) */\n name?: string;\n /** Detailed description of what this permission allows (optional) */\n description?: string;\n /** Detailed error message of what must be returned on forbidden response (optional)\n *\n * Note: not yet implemented\n * */\n errorMessage?: string;\n};\n\n/**\n * Rules defining access control for different controller actions.\n * The array contains role names that are allowed to perform the action.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n *\n * const rules: AccessControlRules = {\n * Create: {\n * roles: [\"Admin\", \"Manager\"],\n * name: \"Create a new user\",\n * description: \"Allows to create a new user\"\n * },\n * Update: [\"Admin\"],\n * Delete: [\"Admin\"],\n * View: [\"Admin\", \"User\", \"Guest\"]\n * };\n *\n */\nexport type AccessControlRules = {\n [key in AccessAction]: string[] | DetailedAccessControlRule | \"*\";\n};\n\n/**\n * Rules defining authentication requirements for different controller actions.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * const authRules: AuthenticationControlRules = {\n * Create: true,\n * Update: true,\n * Delete: true,\n * View: false // Public access\n * };\n */\nexport type AuthenticationControlRules = {\n [key in AccessAction]: boolean;\n};\n\n/**\n * Configuration for authentication control.\n *\n * @example\n * // All actions require authentication\n * const config1: AuthenticationControlConfig = true;\n *\n * // Specific rules per action\n * const config2: AuthenticationControlConfig = {\n * Create: true,\n * View: false\n * };\n */\nexport type AuthenticationControlConfig =\n | boolean\n | Partial<AuthenticationControlRules>;\n\n/**\n * Configuration for access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#auth-config-files---static-rbac}\n * @example\n * // All actions allowed for these roles\n * const config1: AccessControlConfig = [\"Admin\", \"Manager\"];\n *\n * // Specific rules per action\n * const config2: AccessControlConfig = {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * };\n */\nexport type AccessControlConfig = string[] | Partial<AccessControlRules> | \"*\";\n\n/**\n * Configuration for authentication and access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * export const authConfig: AuthConfigs = {\n * authenticationControl: {\n * Create: true,\n * View: false\n * },\n * accessControl: {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * }\n * };\n */\nexport type AuthConfigs = {\n authenticationControl?: AuthenticationControlConfig;\n accessControl?: AccessControlConfig;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n *\n * @example\n * const payload: AuthJwtPayload = {\n * id: 123,\n * roles: [\"Admin\"],\n * email: \"user@example.com\"\n * };\n */\nexport interface AuthJwtPayload extends JwtPayload {\n id?: number | string;\n [x: string]: any;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { Router } from "express";
2
2
  import RouteConfigValidator from "./route-config-validator.js";
3
3
  import RouteConfigRegistry from "./route-config-registry.js";
4
- import { extractArkosRoutes, extractPathParams, getMiddlewareStack, } from "./utils/helpers/index.js";
4
+ import { applyPrefix, extractArkosRoutes, extractPathParams, getMiddlewareStack, } from "./utils/helpers/index.js";
5
5
  import { getArkosConfig } from "../../exports/index.js";
6
6
  import { catchAsync } from "../../exports/error-handler/index.js";
7
7
  import zodToJsonSchema from "zod-to-json-schema";
@@ -29,20 +29,26 @@ export default function ArkosRouter(options) {
29
29
  return function (config, ...handlers) {
30
30
  if (config.disabled)
31
31
  return;
32
- const path = config.path;
33
32
  if (!RouteConfigValidator.isArkosRouteConfig(config))
34
33
  throw Error(`First argument of ArkosRouter().${prop}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === "object" ? JSON.stringify(config, null, 2) : config}`);
34
+ const path = applyPrefix(options?.prefix, config.path);
35
+ config = { ...config, path };
35
36
  if ([null, undefined].includes(path))
36
37
  throw Error("Please pass valid value for path field to use in your route");
37
38
  const method = prop;
39
+ const UndefinedHandlerError = (handler) => Error(`Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`);
38
40
  if (handlers.length > 0) {
39
41
  handlers = handlers.map((handler) => {
42
+ if (!handler)
43
+ throw UndefinedHandlerError(handler);
40
44
  return typeof handler === "function"
41
45
  ? catchAsync(handler, {
42
46
  type: handler.length > 3 ? "error" : "normal",
43
47
  })
44
48
  : Array.isArray(handler)
45
49
  ? handler.map((nesteHandler) => {
50
+ if (!handler)
51
+ throw UndefinedHandlerError(nesteHandler);
46
52
  if (typeof nesteHandler === "function")
47
53
  return;
48
54
  catchAsync(nesteHandler, {
@@ -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,oBAAoB,MAAM,0BAA0B,CAAC;AAC5D,OAAO,mBAAmB,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,OAAO,eAAe,MAAM,oBAAoB,CAAC;AACjD,OAAO,0BAA0B,MAAM,oEAAoE,CAAC;AAC5G,OAAO,sBAAsB,MAAM,8DAA8D,CAAC;AAClG,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AA0B7D,MAAM,CAAC,OAAO,UAAU,WAAW,CAAC,OAAuB;IACzD,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAE/B,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM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C,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,IAAI,EAAE;YACtC,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAC9C,UAAU,EAAE,aAAa;YACzB,GAAG,CAAC,CAAC,gBAAgB,CAAC,WAAW;gBAC/B,MAAM,EAAE,UAAU;gBAClB,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI;gBAC1B,WAAW,EAAE;oBACX,OAAO,EAAE;wBACP,kBAAkB,EAAE;4BAClB,MAAM,EAAE,qBAAqB,CAAC,MAAM,EAAE,UAAU,EAAE,IAAW,CAAC;yBAC/D;qBACF;iBACF;aACF,CAAC;YACJ,GAAG,gBAAgB;SACpB,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 RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport {\n extractArkosRoutes,\n extractPathParams,\n getMiddlewareStack,\n} from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\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(options?: RouterOptions): IArkosRouter {\n const router = Router(options);\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n const path = config.path;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n 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\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) => {\n return typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : Array.isArray(handler)\n ? handler.map((nesteHandler: any) => {\n if (typeof nesteHandler === \"function\") return;\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n });\n return nesteHandler;\n })\n : handler;\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 (!validationConfig?.resolver && config.validation)\n throw Error(\n `Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n `Trying to authenticate route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication-system.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n 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.jsonSchemaToOpeApiParameters(\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 )\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\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: {\n \"application/json\": {\n schema: validatorToJsonSchema(config?.validation?.body as any),\n },\n },\n },\n }),\n ...convertedOpenAPI,\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,oBAAoB,MAAM,0BAA0B,CAAC;AAC5D,OAAO,mBAAmB,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,OAAO,eAAe,MAAM,oBAAoB,CAAC;AACjD,OAAO,0BAA0B,MAAM,oEAAoE,CAAC;AAC5G,OAAO,sBAAsB,MAAM,8DAA8D,CAAC;AAClG,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AA0B7D,MAAM,CAAC,OAAO,UAAU,WAAW,CACjC,OAEC;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAE/B,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;YAE3D,MAAM,WAAW,GAAG;gBAClB,KAAK;gBACL,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,QAAQ;gBACR,KAAK;gBACL,MAAM;gBACN,OAAO;gBACP,SAAS;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C,GAAG,KAAK,CAAC,IAAI,GAAG,CAAC;gBACvD,KAAK,CAAC,EAAE,KAAK,MAAM;gBAEnB,MAAM,IAAI,KAAK,CACb,qDAAqD,KAAK,CAAC,IAAI,4CAA4C,YAAY,EAAE,CAC1H,CAAC;QACN,CAAC;QAED,OAAO,gBAAgB,CAAC,UAAU,CAAC;QAElC,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,IAAI,EAAE;YACtC,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAC9C,UAAU,EAAE,aAAa;YACzB,GAAG,CAAC,CAAC,gBAAgB,CAAC,WAAW;gBAC/B,MAAM,EAAE,UAAU;gBAClB,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI;gBAC1B,WAAW,EAAE;oBACX,OAAO,EAAE;wBACP,kBAAkB,EAAE;4BAClB,MAAM,EAAE,qBAAqB,CAAC,MAAM,EAAE,UAAU,EAAE,IAAW,CAAC;yBAC/D;qBACF;iBACF;aACF,CAAC;YACJ,GAAG,gBAAgB;SACpB,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 RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport {\n applyPrefix,\n extractArkosRoutes,\n extractPathParams,\n getMiddlewareStack,\n} from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(\n options?: RouterOptions & {\n prefix?: string | RegExp | Array<string | RegExp>;\n }\n): IArkosRouter {\n const router = Router(options);\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const path = applyPrefix(options?.prefix, config.path);\n\n config = { ...config, path };\n\n if ([null, undefined].includes(path as any))\n throw Error(\n \"Please pass valid value for path field to use in your route\"\n );\n\n const method = prop as string;\n const UndefinedHandlerError = (handler: any) =>\n Error(\n `Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`\n );\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) => {\n if (!handler) throw UndefinedHandlerError(handler);\n\n return typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : Array.isArray(handler)\n ? handler.map((nesteHandler: any) => {\n if (!handler) throw UndefinedHandlerError(nesteHandler);\n\n if (typeof nesteHandler === \"function\") return;\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n });\n return nesteHandler;\n })\n : handler;\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 (!validationConfig?.resolver && config.validation)\n throw Error(\n `Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n `Trying to authenticate route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication-system.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n 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.jsonSchemaToOpeApiParameters(\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 )\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\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: {\n \"application/json\": {\n schema: validatorToJsonSchema(config?.validation?.body as any),\n },\n },\n },\n }),\n ...convertedOpenAPI,\n };\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 { IRouter } from \"express\";\nimport { 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 PathParams = string | RegExp | Array<string | RegExp>;\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 MethodHandler<T> = (\n config: ArkosRouteConfig | PathParams,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n) => T;\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: MethodHandler<this>;\n /** POST method handler with route configuration support */\n post: MethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: MethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: MethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: MethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: MethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: MethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: MethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: MethodHandler<this>;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig = {\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?: ZodSchema | (new (...args: any[]) => object) | false;\n body?: ZodSchema | (new (...args: any[]) => object) | false;\n params?: ZodSchema | (new (...args: any[]) => object) | false;\n };\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 { IRouter } from \"express\";\nimport { ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport {\n AccessControlConfig,\n AccessControlRules,\n DetailedAccessControlRule,\n} 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 PathParams = string | RegExp | Array<string | RegExp>;\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 MethodHandler<T> = (\n config: ArkosRouteConfig | PathParams,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n) => T;\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: MethodHandler<this>;\n /** POST method handler with route configuration support */\n post: MethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: MethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: MethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: MethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: MethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: MethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: MethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: MethodHandler<this>;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig = {\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?: AccessControlConfig;\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?: ZodSchema | (new (...args: any[]) => object) | false;\n body?: ZodSchema | (new (...args: any[]) => object) | false;\n params?: ZodSchema | (new (...args: any[]) => object) | false;\n };\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"]}
@@ -99,4 +99,54 @@ export function extractPathParams(path) {
99
99
  }
100
100
  return params;
101
101
  }
102
+ export function applyPrefix(prefix = "", path) {
103
+ if (!prefix)
104
+ return path;
105
+ const prefixArr = Array.isArray(prefix) ? prefix : [prefix];
106
+ const pathArr = Array.isArray(path) ? path : [path];
107
+ const result = [];
108
+ for (const pfx of prefixArr) {
109
+ for (const pth of pathArr) {
110
+ result.push(applySinglePrefix(pfx, pth));
111
+ }
112
+ }
113
+ return result.length === 1 ? result[0] : result;
114
+ }
115
+ function applySinglePrefix(prefix, path) {
116
+ const isPrefixRegex = prefix instanceof RegExp;
117
+ const isPathRegex = path instanceof RegExp;
118
+ if (typeof prefix === "string" && typeof path === "string") {
119
+ const normalizedPrefix = prefix.endsWith("/")
120
+ ? prefix.slice(0, -1)
121
+ : prefix;
122
+ return `${normalizedPrefix}${path.startsWith("/") ? "" : "/"}${path}`;
123
+ }
124
+ if (typeof prefix === "string" && isPathRegex) {
125
+ const escapedPrefix = prefix
126
+ .replace(/\/$/, "")
127
+ .replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
128
+ const source = path.source.startsWith("^")
129
+ ? path.source.slice(1)
130
+ : path.source;
131
+ return new RegExp(`^${escapedPrefix}${source}`, path.flags);
132
+ }
133
+ if (isPrefixRegex && typeof path === "string") {
134
+ const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
135
+ const prefixSource = prefix.source.endsWith("$")
136
+ ? prefix.source.slice(0, -1)
137
+ : prefix.source;
138
+ return new RegExp(`^${prefixSource}${escapedPath}`, prefix.flags);
139
+ }
140
+ if (isPrefixRegex && isPathRegex) {
141
+ const prefixSource = prefix.source.endsWith("$")
142
+ ? prefix.source.slice(0, -1)
143
+ : prefix.source;
144
+ const pathSource = path.source.startsWith("^")
145
+ ? path.source.slice(1)
146
+ : path.source;
147
+ const flags = Array.from(new Set([...prefix.flags, ...path.flags])).join("");
148
+ return new RegExp(`^${prefixSource}${pathSource}`, flags);
149
+ }
150
+ throw new TypeError("Invalid prefix or path");
151
+ }
102
152
  //# sourceMappingURL=index.js.map