Skip to content

Conversation

@Jatin24062005
Copy link

@Jatin24062005 Jatin24062005 commented Jan 7, 2026

Description

This PR introduces centralized and structured error handling for language and framework resolution in @asyncapi/generator-components.

What was the problem?

  • Language/framework resolution logic was duplicated across multiple components.
  • Unsupported languages or missing/unsupported frameworks resulted in silent failures or unclear runtime errors (e.g. undefined is not a function).
  • Error messages were inconsistent and difficult for users to understand.

What this PR does

  • Introduces a single centralized resolver (resolveLanguageConfig) to handle:

    • Unsupported languages
    • Missing frameworks (only when required)
    • Unsupported frameworks
    • Invalid configuration shapes
  • Adds a shared GeneratorError class to provide:

    • Clear, user-facing error messages
    • Consistent error codes and metadata
  • Refactors MethodGenerator and related components to rely on the centralized resolver instead of local logic.

  • Adds unit tests for the resolver covering all supported configuration patterns:

    • Function-based configs
    • Direct language configs
    • Framework-based configs (e.g. Java/Quarkus)

Why this approach

  • Keeps individual components declarative and DRY
  • Ensures consistent behavior and error messages across all templates
  • Makes it easier to extend support for new languages/frameworks in the future
  • Improves developer and user experience without changing template APIs

Related issue(s)

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved error handling for code generation with structured, code-associated error messages and metadata support.
    • Centralized configuration resolution for language and framework specifications across all generators.
  • Refactor

    • Streamlined code generation logic by consolidating language-specific configuration handling into a unified utility.
  • Tests

    • Added comprehensive test coverage for configuration resolution, including unsupported languages, frameworks, and error scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Jan 7, 2026

⚠️ No Changeset found

Latest commit: 9489d67

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@asyncapi-bot
Copy link
Contributor

What reviewer looks at during PR review

The following are ideal points maintainers look for during review. Reviewing these points yourself beforehand can help streamline the review process and reduce time to merge.

  1. PR Title: Use a concise title that follows our Conventional Commits guidelines and clearly summarizes the change using imperative mood (it means spoken or written as if giving a command or instruction, like "add new helper for listing operations")

    Note - In Generator, prepend feat: or fix: in PR title only when PATCH/MINOR release must be triggered.

  2. PR Description: Clearly explain the issue being solved, summarize the changes made, and mention the related issue.

    Note - In Generator, we use Maintainers Work board to track progress. Ensure the PR Description includes Resolves #<issue-number> or Fixes #<issue-number> this will automatically close the linked issue when the PR is merged and helps automate the maintainers workflow.

  3. Documentation: Update the relevant Generator documentation to accurately reflect the changes introduced in the PR, ensuring users and contributors have up-to-date guidance.

  4. Comments and JSDoc: Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions, so others can easily understand and use the code.

  5. DRY Code: Ensure the code follows the Don't Repeat Yourself principle. Look out for duplicate logic that can be reused.

  6. Test Coverage: Ensure the new code is well-tested with meaningful test cases that pass consistently and cover all relevant edge cases.

  7. Commit History: Contributors should avoid force-pushing as much as possible. It makes it harder to track incremental changes and review the latest updates.

  8. Template Design Principles Alignment: While reviewing template-related changes in the packages/ directory, ensure they align with the Assumptions and Principles. If any principle feels outdated or no longer applicable, start a discussion these principles are meant to evolve with the project.

  9. Reduce Scope When Needed: If an issue or PR feels too large or complex, consider splitting it and creating follow-up issues. Smaller, focused PRs are easier to review and merge.

  10. Bot Comments: As reviewers, check that contributors have appropriately addressed comments or suggestions made by automated bots. If there are bot comments the reviewer disagrees with, react to them or mark them as resolved, so the review history remains clear and accurate.

@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2026

📝 Walkthrough

Walkthrough

This change introduces a centralized error handling mechanism and language configuration resolution system. It refactors two component files to use a new resolveLanguageConfig utility, adds a GeneratorError class for structured error reporting with metadata, and includes comprehensive tests for the new configuration resolver.

Changes

Cohort / File(s) Change Summary
Error Handling Infrastructure
packages/components/src/errors/GeneratorError.js
New error class extending Error with constructor accepting (code, message, meta = {}). Sets name to 'GeneratorComponentError' and stores code and metadata for structured error reporting.
Configuration Resolution
packages/components/src/utils/resolveLanguageConfig.js
New utility function that resolves language-specific configuration with support for three config shapes: function-based, direct object, and framework-based. Validates language/framework support and provides detailed error payloads via GeneratorError.
Component Refactoring
packages/components/src/components/MethodGenerator.js, packages/components/src/components/QueryParamsVariables.js
Both components refactored to replace inline language/framework-specific resolution logic with calls to resolveLanguageConfig. Removed internal resolver functions (resolveDocsAndLogic, resolveQueryParamLogic). Imports added for resolveLanguageConfig. Public API signatures unchanged.
Test Coverage
packages/components/test/components/resolveLanguageConfig.test.js
New comprehensive test file covering resolveLanguageConfig functionality: unsupported languages, function-based configs, direct method configs, framework-based configs, missing/unsupported frameworks, and invalid config shapes with appropriate error validation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: proper error handling for @async-api/generator-components' clearly summarizes the main change of introducing centralized error handling, uses imperative mood appropriately, and follows Conventional Commits guidelines with 'feat:' prefix.
Linked Issues check ✅ Passed The pull request successfully implements proper error handling for @asyncapi/generator-components by introducing GeneratorError class and resolveLanguageConfig utility that provides accurate user-facing error messages for unsupported languages, missing/unsupported frameworks, and invalid configurations [#1712].
Out of Scope Changes check ✅ Passed All changes are directly scoped to error handling implementation: GeneratorError class, resolveLanguageConfig utility, refactored MethodGenerator and QueryParamsVariables to use centralized resolver, and corresponding unit tests.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Jan 7, 2026

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/components/src/components/QueryParamsVariables.js (1)

91-97: Remove orphaned JSDoc comment.

Lines 91-97 contain a JSDoc comment describing a resolveQueryParamLogic function that no longer exists (replaced by resolveLanguageConfig). This orphaned documentation should be removed.

🧹 Proposed fix
-/**
- * Resolve the appropriate query parameter configuration function based on language and framework.
- *
- * @param {SupportedLanguage} language - The target programming language.
- * @param {string} [framework=''] - Optional framework (e.g., 'quarkus' for Java).
- * @returns {function} The configuration function for generating query parameter code.
- */
-
🤖 Fix all issues with AI agents
In @packages/components/src/components/QueryParamsVariables.js:
- Around line 114-119: Document that generateParamCode (result of
resolveLanguageConfig using queryParamLogicConfig, language, and framework) can
throw GeneratorError variants like UNSUPPORTED_LANGUAGE, UNSUPPORTED_FRAMEWORK,
MISSING_FRAMEWORK, or invalid config by adding JSDoc @throws to the
QueryParamsVariables component describing these conditions; wrap the
resolveLanguageConfig call (generateParamCode) in a try-catch that catches
GeneratorError (check error.name or instanceof GeneratorError) and handle it
gracefully by either rendering a clear fallback/error UI message or rethrowing a
normalized Error so a parent error boundary can catch it; ensure the catch
includes the language/framework values in the log/ message to aid debugging.

In @packages/components/src/errors/GeneratorError.js:
- Around line 1-8: Add JSDoc to the GeneratorError class and its constructor:
document the class purpose, the constructor parameters (code: string|number,
message: string, meta: object = {}), the possible/expected error codes and their
meaning, and the structure/types of the meta object (optional fields and
examples). Include @class, @extends Error, @param tags for code, message, and
meta, an @property annotation for name/code/meta on the instance, and an
@example showing typical usage when throwing new GeneratorError(...). Ensure the
JSDoc sits immediately above the class declaration for GeneratorError and
mentions GeneratorComponentError as the instance name.

In @packages/components/src/utils/resolveLanguageConfig.js:
- Around line 3-57: Add a JSDoc block above the resolveLanguageConfig function
that explains its purpose (resolve per-language or per-framework generation
config), documents parameters (config: object mapping languages to configs,
language: string, framework?: string, context: string), states the return type
(either a function or an object with methodLogic/methodDocs or a
framework-specific object), and lists possible thrown errors with their codes
and conditions (GeneratorError: 'UNSUPPORTED_LANGUAGE' when language missing,
'UNSUPPORTED_FRAMEWORK' when framework not found, 'MISSING_FRAMEWORK' when
framework required but not provided, and 'INVALID_LANGUAGE_CONFIG' for
unexpected config shape); include brief examples or notes about the three config
cases (function-based, direct method config, framework-based) and mention the
shape of supportedFrameworks/supportedLanguages in the error metadata.
🧹 Nitpick comments (5)
packages/components/src/errors/GeneratorError.js (1)

4-4: Consider aligning the error name with the class name.

The class is named GeneratorError but this.name is set to 'GeneratorComponentError'. This inconsistency might confuse developers checking error types in logs or error handlers.

packages/components/src/components/MethodGenerator.js (1)

69-71: Enhance JSDoc comment for the resolution logic.

The inline comment is minimal. Consider adding more detail about the resolution behavior and fallback mechanism for future maintainers.

📝 Suggested enhancement
-  
-/**
- * Resolve docs and logic for the given language + framework config.
- */
+/**
+ * Resolve language/framework-specific method documentation and logic.
+ * Uses resolveLanguageConfig when methodConfig is provided.
+ * Falls back to methodDocs/methodLogic props if the resolved config doesn't override them.
+ * @throws {GeneratorError} If language is unsupported or framework is missing/unsupported.
+ */
packages/components/test/components/resolveLanguageConfig.test.js (1)

13-28: Consider consolidating duplicate assertions.

Lines 13-19 and 21-27 test the same scenario with identical setup. You can combine these into a single expectation that checks both the error type and message:

♻️ Proposed refactor
-      expect(() =>
-        resolveLanguageConfig({
-          config,
-          language: 'python',
-          context
-        })
-      ).toThrow(GeneratorError);
-
-      expect(() =>
-        resolveLanguageConfig({
-          config,
-          language: 'python',
-          context
-        })
-      ).toThrow('Language "python" is not supported');
+      expect(() =>
+        resolveLanguageConfig({
+          config,
+          language: 'python',
+          context
+        })
+      ).toThrow(expect.objectContaining({
+        name: 'GeneratorComponentError',
+        message: expect.stringContaining('Language "python" is not supported')
+      }));

Apply similar refactoring to other duplicate assertions in the file (lines 87-103, 105-123, 132-146).

packages/components/src/utils/resolveLanguageConfig.js (2)

24-30: Strengthen validation for Case 2 (direct method config).

The condition ('methodLogic' in langConfig || 'methodDocs' in langConfig) may match objects that aren't actually valid method configs. An object could have only one of these properties or could have additional unexpected properties.

Consider validating that:

  • At least one expected property exists
  • The object doesn't look like a framework-based config (no nested framework keys)
🔍 Proposed validation enhancement
  // Case 2: direct method config (NO frameworks)
  if (
    typeof langConfig === 'object' &&
-    ('methodLogic' in langConfig || 'methodDocs' in langConfig)
+    ('methodLogic' in langConfig || 'methodDocs' in langConfig) &&
+    !Object.values(langConfig).some(val => typeof val === 'object' && ('methodLogic' in val || 'methodDocs' in val))
  ) {
    return langConfig;
  }

This additional check ensures we don't accidentally match framework-based configs as direct configs.


34-36: Add validation for framework config shape.

Lines 34-36 return langConfig[framework] without verifying it's a valid config (function or object). If someone misconfigures and sets a framework to a primitive value like true or a string, this could cause runtime errors downstream.

🛡️ Proposed validation
  if (typeof langConfig === 'object') {
    if (framework && langConfig[framework]) {
+      const frameworkConfig = langConfig[framework];
+      if (typeof frameworkConfig !== 'function' && typeof frameworkConfig !== 'object') {
+        throw new GeneratorError(
+          'INVALID_FRAMEWORK_CONFIG',
+          `Invalid configuration for framework "${framework}" in ${language} for ${context}.`
+        );
+      }
-      return langConfig[framework];
+      return frameworkConfig;
    }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c49e8aa and 9489d67.

📒 Files selected for processing (5)
  • packages/components/src/components/MethodGenerator.js
  • packages/components/src/components/QueryParamsVariables.js
  • packages/components/src/errors/GeneratorError.js
  • packages/components/src/utils/resolveLanguageConfig.js
  • packages/components/test/components/resolveLanguageConfig.test.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/pr-review-checklist.md)

Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions

Files:

  • packages/components/test/components/resolveLanguageConfig.test.js
  • packages/components/src/errors/GeneratorError.js
  • packages/components/src/components/QueryParamsVariables.js
  • packages/components/src/components/MethodGenerator.js
  • packages/components/src/utils/resolveLanguageConfig.js
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
Repo: asyncapi/generator PR: 0
File: .github/pr-review-checklist.md:0-0
Timestamp: 2026-01-05T09:57:34.791Z
Learning: Update relevant Generator documentation to accurately reflect PR changes introduced
📚 Learning: 2026-01-05T09:57:44.273Z
Learnt from: CR
Repo: asyncapi/generator PR: 0
File: Development.md:0-0
Timestamp: 2026-01-05T09:57:44.273Z
Learning: Applies to apps/generator/test/**/*.test.{js,ts} : Create new test files in the appropriate directory under apps/generator/test/ and follow existing test patterns

Applied to files:

  • packages/components/test/components/resolveLanguageConfig.test.js
📚 Learning: 2026-01-05T09:57:34.791Z
Learnt from: CR
Repo: asyncapi/generator PR: 0
File: .github/pr-review-checklist.md:0-0
Timestamp: 2026-01-05T09:57:34.791Z
Learning: Update relevant Generator documentation to accurately reflect PR changes introduced

Applied to files:

  • packages/components/src/errors/GeneratorError.js
  • packages/components/src/components/MethodGenerator.js
🧬 Code graph analysis (3)
packages/components/test/components/resolveLanguageConfig.test.js (2)
packages/components/src/utils/resolveLanguageConfig.js (1)
  • resolveLanguageConfig (3-57)
packages/components/src/errors/GeneratorError.js (1)
  • GeneratorError (1-8)
packages/components/src/components/QueryParamsVariables.js (1)
packages/components/src/utils/resolveLanguageConfig.js (1)
  • resolveLanguageConfig (3-57)
packages/components/src/components/MethodGenerator.js (2)
packages/components/src/components/readme/CoreMethods.js (1)
  • methodConfig (3-12)
packages/components/src/utils/resolveLanguageConfig.js (1)
  • resolveLanguageConfig (3-57)
🔇 Additional comments (5)
packages/components/src/components/QueryParamsVariables.js (1)

3-3: LGTM! Clean integration of centralized resolver.

The import of resolveLanguageConfig properly integrates the centralized language configuration resolution mechanism.

packages/components/src/components/MethodGenerator.js (2)

2-2: LGTM! Clean integration of centralized resolver.

The import of resolveLanguageConfig properly integrates the centralized language configuration resolution mechanism into the MethodGenerator component.


67-86: Good refactoring with proper fallback handling.

The resolution logic correctly:

  • Only resolves when methodConfig is provided (preserving backward compatibility)
  • Uses resolveLanguageConfig for centralized error handling
  • Falls back to prop values (methodDocs, methodLogic) using nullish coalescing
  • Passes appropriate context for error messages
packages/components/test/components/resolveLanguageConfig.test.js (1)

1-149: Excellent test coverage for the resolver.

The test suite comprehensively covers all major scenarios:

  • Unsupported languages
  • Function-based configs
  • Direct method configs without frameworks
  • Framework-based configs (with proper framework, missing framework, unsupported framework)
  • Invalid config shapes

The tests verify both error types and error messages, ensuring proper error handling.

packages/components/src/utils/resolveLanguageConfig.js (1)

9-17: Good error handling with helpful metadata.

The unsupported language check provides clear error messages and includes supportedLanguages in the meta object, which helps users quickly identify valid options.

Comment on lines +114 to +119
const generateParamCode = resolveLanguageConfig({
config: queryParamLogicConfig,
language,
framework,
context: 'query parameter generation'
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for error handling patterns around QueryParamsVariables usage
rg -nP -A5 -B5 'QueryParamsVariables' --type=js --type=jsx

Repository: asyncapi/generator

Length of output: 89


🏁 Script executed:

#!/bin/bash
# Examine the QueryParamsVariables.js file to understand context and error handling
cd packages/components/src/components
wc -l QueryParamsVariables.js

Repository: asyncapi/generator

Length of output: 89


🏁 Script executed:

#!/bin/bash
# Search for try-catch blocks or error handling in the component file itself
rg -n 'try|catch|error|Error|boundary|ErrorBoundary' packages/components/src/components/QueryParamsVariables.js

Repository: asyncapi/generator

Length of output: 117


🏁 Script executed:

#!/bin/bash
# Search for resolveLanguageConfig to understand its error behavior
rg -n -B5 -A10 'resolveLanguageConfig' packages/components/src/components/QueryParamsVariables.js

Repository: asyncapi/generator

Length of output: 1082


🏁 Script executed:

#!/bin/bash
# View the complete context of lines 100-143 to understand the function scope
sed -n '100,143p' packages/components/src/components/QueryParamsVariables.js

Repository: asyncapi/generator

Length of output: 1462


🏁 Script executed:

#!/bin/bash
# Check the resolveLanguageConfig implementation to understand error behavior
find . -name 'resolveLanguageConfig*' -type f

Repository: asyncapi/generator

Length of output: 186


🏁 Script executed:

#!/bin/bash
# Search for usage of QueryParamsVariables in templates or parent components
rg -n 'QueryParamsVariables' --type=js

Repository: asyncapi/generator

Length of output: 1775


🏁 Script executed:

#!/bin/bash
# Search for error boundaries (try-catch, ErrorBoundary) in the generator project
rg -n 'ErrorBoundary|try\s*{' packages/components/src --type=js

Repository: asyncapi/generator

Length of output: 167


🏁 Script executed:

#!/bin/bash
# Read the resolveLanguageConfig implementation
cat -n packages/components/src/utils/resolveLanguageConfig.js

Repository: asyncapi/generator

Length of output: 1913


🏁 Script executed:

#!/bin/bash
# Check the test file to understand error handling expectations
cat -n packages/components/test/components/QueryParamsVariables.test.js

Repository: asyncapi/generator

Length of output: 3343


🏁 Script executed:

#!/bin/bash
# Check one of the template usages to see if error boundaries are used
head -50 packages/templates/clients/websocket/python/components/Constructor.js

Repository: asyncapi/generator

Length of output: 1624


🏁 Script executed:

#!/bin/bash
# Search for error handling patterns in templates
rg -n 'try|catch|error|Error' packages/templates/clients/websocket/python/components/Constructor.js

Repository: asyncapi/generator

Length of output: 125


Document error conditions in JSDoc and add error handling for unsupported languages/frameworks.

The resolveLanguageConfig call throws GeneratorError for unsupported languages (e.g., UNSUPPORTED_LANGUAGE), unsupported frameworks (UNSUPPORTED_FRAMEWORK), missing frameworks (MISSING_FRAMEWORK), or invalid configurations. Currently, the component lacks:

  • JSDoc documentation of error conditions (required by coding guidelines for .js files)
  • Try-catch handling in the component
  • Error boundaries or error handling in parent components

Add JSDoc @throws documentation and ensure either the component handles these errors gracefully or parent templates wrap it in error boundaries.

🤖 Prompt for AI Agents
In @packages/components/src/components/QueryParamsVariables.js around lines 114
- 119, Document that generateParamCode (result of resolveLanguageConfig using
queryParamLogicConfig, language, and framework) can throw GeneratorError
variants like UNSUPPORTED_LANGUAGE, UNSUPPORTED_FRAMEWORK, MISSING_FRAMEWORK, or
invalid config by adding JSDoc @throws to the QueryParamsVariables component
describing these conditions; wrap the resolveLanguageConfig call
(generateParamCode) in a try-catch that catches GeneratorError (check error.name
or instanceof GeneratorError) and handle it gracefully by either rendering a
clear fallback/error UI message or rethrowing a normalized Error so a parent
error boundary can catch it; ensure the catch includes the language/framework
values in the log/ message to aid debugging.

Comment on lines +1 to +8
export class GeneratorError extends Error {
constructor(code, message, meta = {}) {
super(message);
this.name = 'GeneratorComponentError';
this.code = code;
this.meta = meta;
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add JSDoc documentation for the GeneratorError class.

The class and its constructor lack JSDoc comments describing parameters, error codes, and the meta structure. As per coding guidelines, all functions and classes should have clear JSDoc comments.

📝 Suggested JSDoc documentation
+/**
+ * Custom error class for generator component errors.
+ * Provides structured error information with error codes and metadata.
+ */
 export class GeneratorError extends Error {
+  /**
+   * @param {string} code - Error code (e.g., 'UNSUPPORTED_LANGUAGE', 'MISSING_FRAMEWORK').
+   * @param {string} message - Human-readable error message.
+   * @param {Object} [meta={}] - Additional metadata (e.g., supportedLanguages, supportedFrameworks).
+   */
   constructor(code, message, meta = {}) {
     super(message);
     this.name = 'GeneratorComponentError';
     this.code = code;
     this.meta = meta;
   }
 }

Based on coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export class GeneratorError extends Error {
constructor(code, message, meta = {}) {
super(message);
this.name = 'GeneratorComponentError';
this.code = code;
this.meta = meta;
}
}
/**
* Custom error class for generator component errors.
* Provides structured error information with error codes and metadata.
*/
export class GeneratorError extends Error {
/**
* @param {string} code - Error code (e.g., 'UNSUPPORTED_LANGUAGE', 'MISSING_FRAMEWORK').
* @param {string} message - Human-readable error message.
* @param {Object} [meta={}] - Additional metadata (e.g., supportedLanguages, supportedFrameworks).
*/
constructor(code, message, meta = {}) {
super(message);
this.name = 'GeneratorComponentError';
this.code = code;
this.meta = meta;
}
}
🤖 Prompt for AI Agents
In @packages/components/src/errors/GeneratorError.js around lines 1 - 8, Add
JSDoc to the GeneratorError class and its constructor: document the class
purpose, the constructor parameters (code: string|number, message: string, meta:
object = {}), the possible/expected error codes and their meaning, and the
structure/types of the meta object (optional fields and examples). Include
@class, @extends Error, @param tags for code, message, and meta, an @property
annotation for name/code/meta on the instance, and an @example showing typical
usage when throwing new GeneratorError(...). Ensure the JSDoc sits immediately
above the class declaration for GeneratorError and mentions
GeneratorComponentError as the instance name.

Comment on lines +3 to +57
export function resolveLanguageConfig({
config,
language,
framework,
context
}) {
const langConfig = config[language];

if (!langConfig) {
throw new GeneratorError(
'UNSUPPORTED_LANGUAGE',
`Language "${language}" is not supported for ${context}.`,
{ supportedLanguages: Object.keys(config) }
);
}

// Case 1: function-based config (python, js, etc.)
if (typeof langConfig === 'function') {
return langConfig;
}

// Case 2: direct method config (NO frameworks)
if (
typeof langConfig === 'object' &&
('methodLogic' in langConfig || 'methodDocs' in langConfig)
) {
return langConfig;
}

// Case 3: framework-based config (java, etc.)
if (typeof langConfig === 'object') {
if (framework && langConfig[framework]) {
return langConfig[framework];
}

if (framework) {
throw new GeneratorError(
'UNSUPPORTED_FRAMEWORK',
`Framework "${framework}" is not supported for ${context} in ${language}.`,
{ supportedFrameworks: Object.keys(langConfig) }
);
}

throw new GeneratorError(
'MISSING_FRAMEWORK',
`Framework must be specified for ${context} in ${language}.`,
{ supportedFrameworks: Object.keys(langConfig) }
);
}

throw new GeneratorError(
'INVALID_LANGUAGE_CONFIG',
`Invalid configuration for ${context} in ${language}.`
);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add comprehensive JSDoc documentation.

The resolveLanguageConfig function lacks JSDoc comments describing its purpose, parameters, return value, and error conditions. As per coding guidelines, all functions should have clear JSDoc documentation.

📝 Suggested JSDoc documentation
+/**
+ * Resolves language and framework-specific configuration for generator components.
+ * Supports three configuration patterns:
+ * 1. Function-based config (e.g., python, javascript)
+ * 2. Direct method config without frameworks (object with methodLogic/methodDocs)
+ * 3. Framework-based config (nested object keyed by framework name)
+ *
+ * @param {Object} params - Resolution parameters.
+ * @param {Object} params.config - Language configuration object.
+ * @param {string} params.language - Target programming language.
+ * @param {string} [params.framework] - Optional framework name (required for framework-based configs).
+ * @param {string} params.context - Context description for error messages (e.g., 'method "handleMessage"').
+ * @returns {Function|Object} Resolved configuration (function or object with methodLogic/methodDocs).
+ * @throws {GeneratorError} When language is unsupported, framework is missing/unsupported, or config is invalid.
+ */
 export function resolveLanguageConfig({

Based on coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function resolveLanguageConfig({
config,
language,
framework,
context
}) {
const langConfig = config[language];
if (!langConfig) {
throw new GeneratorError(
'UNSUPPORTED_LANGUAGE',
`Language "${language}" is not supported for ${context}.`,
{ supportedLanguages: Object.keys(config) }
);
}
// Case 1: function-based config (python, js, etc.)
if (typeof langConfig === 'function') {
return langConfig;
}
// Case 2: direct method config (NO frameworks)
if (
typeof langConfig === 'object' &&
('methodLogic' in langConfig || 'methodDocs' in langConfig)
) {
return langConfig;
}
// Case 3: framework-based config (java, etc.)
if (typeof langConfig === 'object') {
if (framework && langConfig[framework]) {
return langConfig[framework];
}
if (framework) {
throw new GeneratorError(
'UNSUPPORTED_FRAMEWORK',
`Framework "${framework}" is not supported for ${context} in ${language}.`,
{ supportedFrameworks: Object.keys(langConfig) }
);
}
throw new GeneratorError(
'MISSING_FRAMEWORK',
`Framework must be specified for ${context} in ${language}.`,
{ supportedFrameworks: Object.keys(langConfig) }
);
}
throw new GeneratorError(
'INVALID_LANGUAGE_CONFIG',
`Invalid configuration for ${context} in ${language}.`
);
}
/**
* Resolves language and framework-specific configuration for generator components.
* Supports three configuration patterns:
* 1. Function-based config (e.g., python, javascript)
* 2. Direct method config without frameworks (object with methodLogic/methodDocs)
* 3. Framework-based config (nested object keyed by framework name)
*
* @param {Object} params - Resolution parameters.
* @param {Object} params.config - Language configuration object.
* @param {string} params.language - Target programming language.
* @param {string} [params.framework] - Optional framework name (required for framework-based configs).
* @param {string} params.context - Context description for error messages (e.g., 'method "handleMessage"').
* @returns {Function|Object} Resolved configuration (function or object with methodLogic/methodDocs).
* @throws {GeneratorError} When language is unsupported, framework is missing/unsupported, or config is invalid.
*/
export function resolveLanguageConfig({
config,
language,
framework,
context
}) {
const langConfig = config[language];
if (!langConfig) {
throw new GeneratorError(
'UNSUPPORTED_LANGUAGE',
`Language "${language}" is not supported for ${context}.`,
{ supportedLanguages: Object.keys(config) }
);
}
// Case 1: function-based config (python, js, etc.)
if (typeof langConfig === 'function') {
return langConfig;
}
// Case 2: direct method config (NO frameworks)
if (
typeof langConfig === 'object' &&
('methodLogic' in langConfig || 'methodDocs' in langConfig)
) {
return langConfig;
}
// Case 3: framework-based config (java, etc.)
if (typeof langConfig === 'object') {
if (framework && langConfig[framework]) {
return langConfig[framework];
}
if (framework) {
throw new GeneratorError(
'UNSUPPORTED_FRAMEWORK',
`Framework "${framework}" is not supported for ${context} in ${language}.`,
{ supportedFrameworks: Object.keys(langConfig) }
);
}
throw new GeneratorError(
'MISSING_FRAMEWORK',
`Framework must be specified for ${context} in ${language}.`,
{ supportedFrameworks: Object.keys(langConfig) }
);
}
throw new GeneratorError(
'INVALID_LANGUAGE_CONFIG',
`Invalid configuration for ${context} in ${language}.`
);
}
🤖 Prompt for AI Agents
In @packages/components/src/utils/resolveLanguageConfig.js around lines 3 - 57,
Add a JSDoc block above the resolveLanguageConfig function that explains its
purpose (resolve per-language or per-framework generation config), documents
parameters (config: object mapping languages to configs, language: string,
framework?: string, context: string), states the return type (either a function
or an object with methodLogic/methodDocs or a framework-specific object), and
lists possible thrown errors with their codes and conditions (GeneratorError:
'UNSUPPORTED_LANGUAGE' when language missing, 'UNSUPPORTED_FRAMEWORK' when
framework not found, 'MISSING_FRAMEWORK' when framework required but not
provided, and 'INVALID_LANGUAGE_CONFIG' for unexpected config shape); include
brief examples or notes about the three config cases (function-based, direct
method config, framework-based) and mention the shape of
supportedFrameworks/supportedLanguages in the error metadata.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

Proper Error handling mechanism for Baked-in Templates

3 participants