Skip to content

Conversation

manuel3108
Copy link
Member

@manuel3108 manuel3108 commented Sep 6, 2025

Imagine parsing an AST, making a few codemods and printing the AST again. All comment handling up until now is based on knowing where exactly the node is located (based on its loc property). While doing codemods you might add new nodes programmatically that therefore do not have any loc property. Thus, esrap understandably fails to print comments for them.

We don't want to move away from handling most comments via loc, as this is by far the most reliable way.

To support the codemod use case, I created a new option additionalComments. These comments use the leading/trailing pattern and are therefore not as accurate as the loc ones, but it's easily possible to add them to the printed code.

const additionalComments = new WeakMap();
additionalComments.set(syntheticNode, [
  { type: 'Line', value: ' Generated during codemod', position: 'leading' }
]);
print(ast, ts({ additionalComments }));

I also considered calling these comments syntheticComments instead of additional, but for me, it didn't feel right. Happy for better suggestions.

Edit: Forgot to mention, this unblocks:

Copy link

changeset-bot bot commented Sep 6, 2025

🦋 Changeset detected

Latest commit: 718afce

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

This PR includes changesets to release 1 package
Name Type
esrap Minor

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

Copy link

pkg-pr-new bot commented Sep 6, 2025

npm i https://pkg.pr.new/sveltejs/esrap@79

commit: 718afce

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

Successfully merging this pull request may close these issues.

1 participant