Skip to content

Conversation

@lightning-sagar
Copy link
Contributor

@lightning-sagar lightning-sagar commented Nov 25, 2025

Description

This PR fixes an issue where template parameters with a default value of false (e.g., singleFile) were not being applied, causing them to appear as undefined inside templates.

The problem was caused by this check:

 const defaultValues = Object.keys(parameters || {}).filter(key => parameters[key].default);

Since false is falsy, it was incorrectly ignored.
The fix updates the condition to properly detect all default values:

const defaultValues = Object.keys(parameters || {}).filter(key => parameters[key].default !== undefined);

How I verified the fix


Related issue(s)

Fixes #1768

Summary by CodeRabbit

  • Bug Fixes

    • Corrected default-value detection so falsy defaults (0, "", false) are recognized and applied, fixing conditional generation and injection of template defaults.
  • Documentation

    • Clarified guidance to align parameter default types with expected validation types to avoid mismatches and generation issues.
  • Chores

    • Added a release note entry describing the fix for template parameter default handling.

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

@changeset-bot
Copy link

changeset-bot bot commented Nov 25, 2025

🦋 Changeset detected

Latest commit: 769253c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@asyncapi/generator Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another 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 Nov 25, 2025

📝 Walkthrough

Walkthrough

Replaced a truthy check with Object.hasOwn when detecting parameter defaults so falsy defaults (false, 0, "") are recognized; updated docs to recommend matching default types to validation; added a changeset noting the fix.

Changes

Cohort / File(s) Summary
Loader Logic Fix
apps/generator/lib/templates/config/loader.js
Use Object.hasOwn(parameters[key], 'default') instead of a truthy check on parameters[key].default to treat falsy default values as valid defaults.
Configuration Documentation
apps/generator/docs/configuration-file.md
Added guidance to align parameter default value types with expected validation types to avoid mismatches.
Release Changeset
.changeset/fix-template-default-params.md
Add patch release note describing the fix for template parameters with falsy default values being ignored.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 follows Conventional Commits with 'fix:' prefix and uses imperative mood to clearly describe fixing default value detection for boolean false parameters.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #1768: fixes default value detection using Object.hasOwn, updates documentation to align default value types, and includes a changeset for the patch release.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the default value detection issue: loader.js fix, documentation update for parameter type alignment, and changeset addition are all in scope.

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


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.

@lightning-sagar
Copy link
Contributor Author

lightning-sagar commented Nov 26, 2025

Note: After fixing this and changing the value from the string "false" to the boolean false, the CSS/JS will generate correctly🫡

By using asyncapi generate fromTemplate test/spec/asyncapi_v3.yml ./ -o dupa --use-new-generator --force-write -p singleFile="false" this command not by -p singleFile=false

@Jatin24062005
Copy link

@lightning-sagar I reviewed the changes you made. Using: filter(key => parameters[key].default !== undefined); which i say is not bad does fix the false issue, but it may introduce new problems. For example, templates can intentionally set: "default": null or even: "default": undefined In those cases, !== undefined would incorrectly treat these values as valid defaults. to Avoid that problem @derberg Solution to use const defaultValues = Object.keys(parameters || {}).filter(key => hasOwnProperty('default')); but it also have a major issue This checks whether the template author actually defined the default field, regardless of its value. It avoids accidentally ignoring defaults like false, 0, or "".

We avoid using obj.hasOwnProperty() directly because it can throw errors if the object does not inherit from Object.prototype. So to Avoid crashing and error we can use explicit version of js something like const defaultValues = Object.keys(parameters || {}).filter(key => Object.prototype.hasOwnProperty.call(parameters[key], "default") );
this guarantees no crashes and works with all template config objects.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

image

@lightning-sagar
Copy link
Contributor Author

lightning-sagar commented Dec 6, 2025

yes, that makes sense. your solution is definitely more robust.
using Object.prototype.hasOwnProperty.call(...) handles both JSON and JS-generated templates safely, and avoids any issues with falsy defaults or prototype-less objects. thanks for the help!

update: I switched to Object.hasOwn(...) initially since it reads cleaner.

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

🧹 Nitpick comments (1)
apps/generator/lib/templates/config/loader.js (1)

48-56: Default detection fix looks correct; consider small cleanup and Object.hasOwn if supported

The switch to Object.prototype.hasOwnProperty.call(parameters[key], "default") correctly treats any explicitly declared default (including false, 0, '', null, undefined) as a default and fixes the original false-is-ignored bug. 👍

Two small, optional refinements:

  1. Normalize parameters once to avoid repeating || {} and slightly tighten the types:
 function loadDefaultValues(templateConfig, templateParams) {
-    const parameters = templateConfig.parameters;
-    const defaultValues = Object.keys(parameters || {}).filter(key => Object.prototype.hasOwnProperty.call(parameters[key],"default"));
+    const parameters = templateConfig.parameters || {};
+    const defaultValues = Object.keys(parameters).filter(key =>
+        Object.prototype.hasOwnProperty.call(parameters[key], 'default')
+    );
  1. If your minimum Node/JS runtime supports it and you want to satisfy Sonar, you can switch to Object.hasOwn in both places:
-    const defaultValues = Object.keys(parameters).filter(key =>
-        Object.prototype.hasOwnProperty.call(parameters[key], 'default')
-    );
+    const defaultValues = Object.keys(parameters).filter(key =>
+        Object.hasOwn(parameters[key], 'default')
+    );
 
-    defaultValues.filter(dv => !Object.prototype.hasOwnProperty.call(templateParams, dv)).forEach(dv =>
+    defaultValues.filter(dv => !Object.hasOwn(templateParams, dv)).forEach(dv =>
         Object.defineProperty(templateParams, dv, {
             enumerable: true,
             get() {
                 return parameters[dv].default;
             }
         })
     );

Please double‑check that Object.hasOwn is available in all Node versions you support before adopting this; otherwise the current implementation is fine and you may just want to tune the static‑analysis rule instead.

📜 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 3a2d80f and a45bc1f.

📒 Files selected for processing (1)
  • apps/generator/lib/templates/config/loader.js (1 hunks)
🧰 Additional context used
🪛 GitHub Check: SonarCloud Code Analysis
apps/generator/lib/templates/config/loader.js

[warning] 49-49: Use 'Object.hasOwn()' instead of 'Object.prototype.hasOwnProperty.call()'.

See more on https://sonarcloud.io/project/issues?id=asyncapi_generator&issues=AZr1oGE4FDjduF-gLNra&open=AZr1oGE4FDjduF-gLNra&pullRequest=1769

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Acceptance tests for generated templates
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Test NodeJS PR - macos-latest
  • GitHub Check: Test NodeJS PR - windows-latest
  • GitHub Check: Test NodeJS PR - ubuntu-latest

derberg and others added 13 commits December 7, 2025 12:15
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
…S` websocket client (asyncapi#1747)

Co-authored-by: Adi-204 <adiboghawala@gmail.com>
Co-authored-by: Adi Boghawala <adiboghawala@192.168.1.5>
Co-authored-by: Chan <bot+chan@asyncapi.io>
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
…i#1753)

Co-authored-by: kartikayy007 <kartikayy6969@gmail.com>
Co-authored-by: Adi Boghawala <adiboghawala@gmail.com>
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
@derberg derberg self-assigned this Jan 7, 2026
@derberg derberg moved this to Todo in Maintainers work Jan 7, 2026
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.

@lightning-sagar change is good. Ignore rabbit.

most important is how did you test that it works? solves the html-template error?

did you do some manual testing?

after v5 release we have dedicated node ./test/cli option to run generator test cli locally from local sources against any template, you can also point to template in your local drive

@lightning-sagar
Copy link
Contributor Author

lightning-sagar commented Jan 11, 2026

Hi @derberg, sorry for the late response...

I was testing this manually in two ways:

  • using npm link between the generator and html-template
  • and by patching the generator code directly inside node_modules

this confirmed the generator fix works (the default singleFile: false is now working)
but, it also exposed an issue on the html-template side: the template currently expects singleFile as a string ("false"), while the generator now correctly provides it as a boolean (false). Because of this type mismatch, CSS/JS conditional generation still doesnt trigger as expected

so, there are two possible solution:

  1. update html-template to treat singleFile as a boolean or
  2. change the default in html-template/package.json to "false" (string) and handle it consistently as a string...

let me know which approach should i move forward with?

Copy link
Member

derberg commented Jan 12, 2026

did you check it with node ./test/cli ?
when you run a command with local cli, and you pass false, are you sure CLI is not affecting the type of passed parameter?

you'd have to verify with docs, and afaik we explain that whatever you pass through CLI, no matter what CLI - it is always string and then you need to properly handle it further. Generator should not guess if false is intentional string or should cast to boolean. If we do casting in Generator, that might be a breaking change

@lightning-sagar
Copy link
Contributor Author

@derberg, yes you are right and I did test this using node ./test/cli.js already

when singleFile is passed via CLI (e.g. -p singleFile=false), the CLI correctly treats it as a string, and that path works as expected...

the issue only appears when singleFile is not passed at all... in that case, loadDefaultValues injects the default from html-template/package.json, where singleFile is defined as false (boolean). That boolean value is then passed directly into the template context... not by cli

so the flow is:

  • CLI param passed -> value is a string ("false") -> works
  • CLI param not passed → default comes from template config → value is boolean (false)
  • therefore template logic expects a string → css/js conditional generation doesnt trigger

I agree the generator should not cast values coming from CLI, as that would be a breaking change.... the generator fix is correct.... the remaining issue is the type mismatch in html-template when handling default (boolean) vs CLI (string) values.

that why we need to update the html-template/package.json, by converting singleFile default value to "false" (string) or update validation

Copy link
Member

derberg commented Jan 14, 2026

ok, then, imho we need to change the default to string: https://github.com/lightning-sagar/html-template/blob/test/template-params/package.json#L93C23-L93C25

please in this PR also explain that if someone uses conditionalGeneration they should make sure that types defined in it, must match the type of default value from parameter config: https://github.com/asyncapi/generator/blob/master/apps/generator/docs/configuration-file.md

@derberg
Copy link
Member

derberg commented Jan 14, 2026

we have asyncapi/html-template#757 that we can already use

@asyncapi-bot
Copy link
Contributor

asyncapi-bot commented Jan 16, 2026

🚀 Docs preview deployed
Below link points directly to the generator docs preview. May the force be with you!
https://6971e843f82fb8c9c52727ee--asyncapi-website.netlify.app/docs/tools/generator

@lightning-sagar
Copy link
Contributor Author

we have asyncapi/html-template#757 that we can already use

yes, that was exactly my main idea as well..
also @derberg, please let me know if the updated docs wording looks ok from your side or if you want any change??

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.

LGTM

@lightning-sagar we can release it, please add changeset. In dev guide there is explanation of release process. We're only releasing @asyncapi/generator.

@Florence-Njeri please look at added docs

@derberg derberg moved this from Todo to In Progress in Maintainers work Jan 21, 2026
@sonarqubecloud
Copy link

@derberg
Copy link
Member

derberg commented Jan 22, 2026

/rtm

@asyncapi-bot asyncapi-bot merged commit 2bfad27 into asyncapi:master Jan 22, 2026
16 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in Maintainers work Jan 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Generator do not handle template params that default to false

7 participants