Skip to content

refactor: move out the loadTemplateConfig from generator.js #1584

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 29 commits into
base: master
Choose a base branch
from

Conversation

ItsRoy69
Copy link

@ItsRoy69 ItsRoy69 commented May 29, 2025

Description

  • Moved the loadTemplateConfig function to separate file for clean code.
  • Renamed and moved the validation function inside template config

Related issue(s)
Resolves #1582

Summary by CodeRabbit

  • Refactor

    • Streamlined template configuration loading and default parameter handling in generators for improved maintainability without changing user experience.
  • Chores

    • Updated internal import paths for consistency and clarity; no impact on functionality or user experience.

Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
Copy link

changeset-bot bot commented May 29, 2025

⚠️ No Changeset found

Latest commit: 6e7077f

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

Copy link

coderabbitai bot commented May 29, 2025

"""

Walkthrough

The changes refactor the template configuration loading logic in the generator by removing internal methods from the Generator class and introducing new external asynchronous loader functions in a dedicated module. Associated import paths and test imports are updated to reflect this modularization, with no other logic or control flow changes.

Changes

Files/Paths Change Summary
apps/generator/lib/generator.js Removed internal private async methods loadTemplateConfig and loadDefaultValues; replaced with wrappers calling external implementations; updated imports accordingly.
apps/generator/lib/templateConfig/loader.js New module exporting async functions loadTemplateConfig and loadDefaultValues to load and process template configuration and default parameter values.
apps/generator/lib/templateConfig/validator.js Updated import paths for utility modules to use parent directory references.
apps/generator/test/generator.test.js Updated import paths for template config validator module in mocks and test setup.
apps/generator/test/templateConfigValidator.test.js Updated import path for validateTemplateConfig function.
apps/generator/lib/mocks/templateConfigValidator.js Updated mock import path for template config validator.

Assessment against linked issues

Objective Addressed Explanation
Move loadTemplateConfig out of generator.js into a new templateConfig/loader.js module (#1582)
Structure template config logic into templateConfig folder with validator.js and loader.js (#1582)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes identified.

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe42537 and cc07481.

📒 Files selected for processing (2)
  • apps/generator/lib/generator.js (2 hunks)
  • apps/generator/lib/templateConfig/loader.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/generator/lib/generator.js
🔇 Additional comments (6)
apps/generator/lib/templateConfig/loader.js (6)

1-7: LGTM! Clean imports and appropriate constants.

The imports are well-organized and the CONFIG_FILENAME constant improves maintainability.


14-26: Excellent input validation implementation.

The function properly validates the input parameter with comprehensive checks for existence, type, and directory status. This addresses potential runtime errors early.


29-41: Well-structured fallback mechanism for configuration loading.

The function correctly attempts to load from .ageneratorrc first and provides appropriate error logging when it fails, allowing graceful fallback to package.json.


43-56: Robust package.json fallback with proper error handling.

The fallback logic correctly attempts to load configuration from package.json and handles both file reading and JSON parsing errors gracefully. The function appropriately returns an empty object when both configuration sources fail.


63-77: Efficient default value implementation using property getters.

The function elegantly uses Object.defineProperty with getters for lazy evaluation of default values, ensuring defaults are only applied to undefined parameters and computed on access rather than upfront.


79-82: Clean module exports following Node.js conventions.

The exports are clear and follow standard module patterns, making both functions available for external use.

✨ 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our contributors guide useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out this issue.

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

Hey @ItsRoy69 Have you run the test by npm run test command?

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

@derberg can you please start the workflow?

Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
@ItsRoy69
Copy link
Author

ItsRoy69 commented May 30, 2025

@ItshMoh Yes, while I ran npm run test, @derberg I found issues related to other files like SendOperation.js, MessageExamples.js and AvailableOperations.js for which many cases are failing (not related to loadTemplateConfig functions), should I create a separate issue/pull request fixing these ?

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

@ItsRoy69 go through these issues.
Change the path of the `templateConfigValidator' in generator.test.js and other files where it is occuring.
The path has been changed so change its path where it has occured.

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

gen_loadtemp_test_ffail_sc

here are some of the issues.
@ItsRoy69

Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
@ItsRoy69
Copy link
Author

@ItshMoh hey, updated the path accordingly and tested out , its passing now.

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

@ItsRoy69 There are also some issues in dart client. fix it.
These are not issues with the generator. It may be because of new changes.
gen_loadTEmp_dart-sc

The snapshots are obselete, generate new ones.

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

@ItsRoy69 also run npm run lint after the changes.
if there is any error npm run lint:fix.
And please also go through the https://github.com/asyncapi/generator/blob/master/CONTRIBUTING.md

Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
@ItsRoy69
Copy link
Author

npm run test

sure, will go through it , noticed many testings are failing in other files, looking into it

@ItsRoy69
Copy link
Author

ItsRoy69 commented May 30, 2025

@ItshMoh the integration issue is separate issue, I guess that can be handled in separate PR as its quite many changes required for that which is not related to template generator error

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

@ItshMoh the integration issue is separate issue, I guess that can be handled in separate PR as its quite many changes required for that which is not related to template generator error

@ItsRoy69 the integration issue is not the separate issue. it is due to the changes we made in this PR. So we need to fix it here. Otherwise how is it gonna be merged?. Look for it

@ItshMoh
Copy link
Contributor

ItshMoh commented May 30, 2025

@ItsRoy69 modify the generator.test.js file. Where the tests are failing due to
gen.loadTemplateConfig and gen.loadDefaultValues these are now not in the generator class.

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: 1

🧹 Nitpick comments (3)
apps/generator/lib/templateConfig/loader.js (3)

7-10: Fix JSDoc annotation inconsistency.

The function is marked as @private but is exported in the module. Consider either removing the @private annotation or adding appropriate public documentation.

 /**
  * Loads the template configuration.
- * @private
+ * @param {Object} context - The generator instance context (bound via .call())
  */

41-45: Fix JSDoc annotation inconsistency.

Same issue as the loadTemplateConfig function - marked as @private but exported.

 /**
  * Loads default values of parameters from template config. If value was already set as parameter it will not be
- * overriden.
- * @private
+ * overridden.
+ * @param {Object} context - The generator instance context (bound via .call())
  */

Note: Also fixed the typo "overriden" → "overridden".


46-58: Consider the context dependency design.

The functions rely heavily on this context (accessing this.templateDir, this.templateConfig, this.templateParams), which requires careful binding when called. While this maintains compatibility with the existing codebase during refactoring, consider whether a more explicit parameter-passing approach might be more maintainable long-term.

For now, the current approach is acceptable given the refactoring context.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 870e622 and cfffd89.

📒 Files selected for processing (3)
  • apps/generator/lib/generator.js (3 hunks)
  • apps/generator/lib/templateConfig/loader.js (1 hunks)
  • apps/generator/lib/templateConfig/validator.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/generator/lib/templateConfig/validator.js
  • apps/generator/lib/generator.js
🔇 Additional comments (1)
apps/generator/lib/templateConfig/loader.js (1)

11-39: Excellent refactoring approach with proper error handling.

The configuration loading logic is well-structured with appropriate fallback mechanisms:

  • Primary attempt: .ageneratorrc (YAML format)
  • Fallback: package.json with generator property
  • Graceful error handling with debug logging

The refactoring successfully extracts this logic from the main generator file while maintaining the same behavior.

@ItsRoy69 ItsRoy69 requested review from ItshMoh June 4, 2025 03:33
@ItshMoh
Copy link
Contributor

ItshMoh commented Jun 4, 2025

@derberg can you run the workflow when you are free, and also if you can review the decoupling part.

@derberg derberg changed the title refactor: move out the loadTemplateConfig from Gigantic generator.js refactor: move out the loadTemplateConfig from generator.js Jun 4, 2025
Copy link
Member

@derberg derberg left a comment

Choose a reason for hiding this comment

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

I'm concerned about loadDefaultValues.call(this) approach

even though it is possible, we don't do it across the whole project. We follow functions composition as it is better for readability

simply better to have loadDefaultValues that accepts an argument templateConfig that are well documented with jsdoc, and it also returns whatever is needed.

this is cool but when really directly only used inside one a class, within the same file

same with loadDefaultValues

can you please refactor?

@derberg derberg moved this to In Progress in Maintainers work Jun 4, 2025
@ItshMoh
Copy link
Contributor

ItshMoh commented Jun 5, 2025

Hey @ItsRoy69 Can you please refactor the code as @derberg suggested?

@ItsRoy69
Copy link
Author

ItsRoy69 commented Jun 6, 2025

Yes, working on it

ItsRoy69 added 2 commits June 6, 2025 13:11
Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
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: 1

♻️ Duplicate comments (1)
apps/generator/lib/templateConfig/loader.js (1)

19-19: ⚠️ Potential issue

Security vulnerability remains unfixed despite previous review

The YAML parsing still uses the unsafe load() method which can execute arbitrary code. This was flagged in a previous review but appears to remain unaddressed despite being marked as resolved.

Apply this fix immediately:

-    const yamlConfig = require('js-yaml').load(yaml);
+    const yamlConfig = require('js-yaml').load(yaml, { schema: require('js-yaml').JSON_SCHEMA });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90899d8 and 4f0cf60.

📒 Files selected for processing (3)
  • apps/generator/lib/generator.js (2 hunks)
  • apps/generator/lib/templateConfig/loader.js (1 hunks)
  • apps/generator/test/generator.test.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/generator/test/generator.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/generator/lib/generator.js
🔇 Additional comments (3)
apps/generator/lib/templateConfig/loader.js (3)

1-5: LGTM: Clean module setup

The imports and constants are well-organized and appropriate for the module's functionality.


49-63: LGTM: Elegant default value implementation

The use of Object.defineProperty with getters provides lazy evaluation of default values, which is an efficient approach. The filtering logic correctly handles undefined parameters.


65-68: LGTM: Clean module exports

The module exports are well-structured and expose the necessary functions.

ItsRoy69 added 3 commits June 6, 2025 16:57
Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
@ItsRoy69
Copy link
Author

ItsRoy69 commented Jun 6, 2025

@ItshMoh refactored the code accordingly, tested npm run lint, npm run test and npm run lint:fix as well

}
})
);
loadDefaultValues() {
Copy link
Member

Choose a reason for hiding this comment

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

why we need this here, also implementation of loadTemplateConfig() if anyway they are both private? what is blocking us from calling loadDefaultValues inside loadTemplateConfig directly in loader.js?

Copy link
Author

Choose a reason for hiding this comment

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

Added loadTemplateConfig.bind(this) and loadDefaultValues.bind(this) to bind the imported function to the class instance instead of implementation of loadTemplateConfig() and loadTemplateConfig() in generator.js

Copy link
Member

Choose a reason for hiding this comment

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

but why did you do it, call or bind add weird complexity to code

we discussed before that sharing this instead of having arguments in functions is causing complexity

Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
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: 1

♻️ Duplicate comments (1)
apps/generator/lib/templateConfig/loader.js (1)

11-41: Verify security fix implementation and add robust input validation.

Despite past review comments indicating these issues were addressed, the current code still shows potential problems:

  1. Security: Line 18 still uses js-yaml.load() which can execute arbitrary code
  2. Input validation: No validation for this.templateDir existence or type

Please verify that the security fixes were properly applied:

#!/bin/bash
# Check if js-yaml is being used safely
rg -A 2 -B 2 "js-yaml.*load" apps/generator/lib/templateConfig/loader.js

# Check for any input validation in the function
rg -A 5 -B 2 "templateDir.*string\|typeof.*templateDir" apps/generator/lib/templateConfig/loader.js
🧹 Nitpick comments (1)
apps/generator/lib/templateConfig/loader.js (1)

48-60: Consider defensive programming for parameter handling.

The function assumes this.templateConfig.parameters and this.templateParams exist. While this may be guaranteed by the calling context, adding defensive checks would improve robustness.

Consider adding safety checks:

 async function loadDefaultValues() {
+  if (!this.templateConfig || !this.templateParams) {
+    log.debug('Missing templateConfig or templateParams, skipping default values');
+    return;
+  }
+  
   const parameters = this.templateConfig.parameters;
   const defaultValues = Object.keys(parameters || {}).filter(key => parameters[key].default);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0c584e and fe42537.

📒 Files selected for processing (3)
  • apps/generator/lib/generator.js (3 hunks)
  • apps/generator/lib/templateConfig/loader.js (1 hunks)
  • apps/generator/test/generator.test.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/generator/test/generator.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/generator/lib/generator.js
🔇 Additional comments (1)
apps/generator/lib/templateConfig/loader.js (1)

62-65: LGTM: Clean module exports.

The module exports are well-structured and follow Node.js conventions.

ItsRoy69 added 2 commits June 9, 2025 18:33
Signed-off-by: ItsRoy69 <jyotirmoyroy649@gmail.com>
@ItshMoh
Copy link
Contributor

ItshMoh commented Jun 17, 2025

hey @Adi-204 Can you please review this PR? It would be a great help.

@Adi-204
Copy link
Contributor

Adi-204 commented Jun 17, 2025

@ItshMoh I looked at PR and it is looking good, but I think @derberg is best person to guide with the changes done in app/generator.

Copy link

Copy link
Member

@derberg derberg left a comment

Choose a reason for hiding this comment

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

the biggest problem here is that the PR is about refactoring, moving code from one place to another - but I see there is some logic added, some sync functions that are not in scope.

also, why even though loadTemplateConfig and loadDefaultValues were moved, they are still having some implementations in the generator.js and are not just used directly there without these implementations

like for example below

loadTemplateConfig() {
    return loadTemplateConfig(this.templateDir).then(config => {
      this.templateConfig = config;
      return this.loadDefaultValues();
    });
  }

this is completely unnecessary

just line 289 await this.loadTemplateConfig(); must be modified, so new function is used, and proper arguments are passed, and this.templateConfig gets assigned whatever loadTemplateConfig returns

and loadDefaultValues should not even be mentioned once in generator.js but should be used internally inside loader.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: In Progress
Development

Successfully merging this pull request may close these issues.

refactor: move out the loadTemplateConfig from Gigantic generator.js
4 participants