Skip to content
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

feat: add warning if some preset import is overridden #29971

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

OrbisK
Copy link
Contributor

@OrbisK OrbisK commented Nov 19, 2024

🔗 Linked issue

#29258

📚 Description

This pr adds a console.warn if the /composables or /utils override some imports from the defined presets.

It implements this in packages/nuxt/src/imports/module.ts (as suggested in #29258). This is not perfect. This pr does not cover/warn about imports from https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/pages/module.ts#L355, for example.

The text of the warning can of course still be adapted/updated.

I have done my best to test it. I tried to stubGlobal('console') but had no luck so far.

output if adding "useState" at /composables

[15:39:33]  WARN  [imports] "useState" is already defined and auto imported from "#app/composables/state" within nuxt itself. Please consider renaming "useState" at /home/robin/WebstormProjects/nuxt/playground/composables/state.ts.

ℹ Running with compatibility version 4                                                                                                                                                                                   15:39:33

 WARN  Duplicated imports "useState", the one from "#app/composables/state" has been ignored and "/home/robin/WebstormProjects/nuxt/playground/composables/state.ts" is used                                              15:39:33


[15:39:33]  WARN  [imports] "useState" is already defined and auto imported from "#app/composables/state" within nuxt itself. Please consider renaming "useState" at /home/robin/WebstormProjects/nuxt/playground/composables/state.ts.

✔ Vite client built in 24ms                                                                                                                                                                                              15:39:33

 WARN  Duplicated imports "useState", the one from "#app/composables/state" has been ignored and "/home/robin/WebstormProjects/nuxt/playground/composables/state.ts" is used     

Summary by CodeRabbit

  • New Features

    • Enhanced import handling with a new presetMap for better tracking of imported presets.
    • Added a warning mechanism for naming conflicts between composables and presets.
    • Improved type declaration generation based on import context.
  • Bug Fixes

    • Refined logic for scanning directories to prioritize imports based on their source.
  • Chores

    • Optimized path resolution by skipping relative import paths for explicitly installed node modules.

@OrbisK OrbisK requested a review from danielroe as a code owner November 19, 2024 14:35
Copy link

stackblitz bot commented Nov 19, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

coderabbitai bot commented Nov 19, 2024

Walkthrough

The changes in this pull request focus on the module.ts file in the Nuxt imports package. A new presetMap has been introduced to manage imported presets and prevent naming conflicts. The regenerateImports function now warns users of potential issues with composables sharing names with presets. The setup function has been updated for better import management, while the cacheImportPaths function has been optimized to skip certain relative paths. Additionally, the addDeclarationTemplates function has been added to generate accurate type declarations based on imports.

Changes

File Path Change Summary
packages/nuxt/src/imports/module.ts - Added presetMap for tracking imported presets.
- Updated regenerateImports to warn on naming conflicts.
- Enhanced setup for better import management.
- Modified cacheImportPaths to skip certain relative paths.
- Added addDeclarationTemplates function for generating type declarations.

Suggested labels

3.x

🐇 In the land of code where the imports play,
A new presetMap has come out to stay.
With warnings for names that might clash,
Our imports now dance in a more orderly sash.
So hop, little rabbit, and code with delight,
For the module's been brightened, oh what a sight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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

🧹 Outside diff range and nitpick comments (1)
packages/nuxt/src/imports/module.ts (1)

135-136: Use the Nuxt logger instead of console.warn.

For consistency and better control over logging levels, consider using the Nuxt logger.warn method instead of console.warn.

Apply this diff to update the logging method:

-  console.warn(`[imports] "${i.as}" is already defined and auto imported from "${preset ?? 'unknown preset'}" within nuxt itself. Please don't name your composable the same as a preset, as it will lead to unexpected behavior.`)
+  logger.warn(`[imports] "${i.as}" is already defined and auto imported from "${preset ?? 'unknown preset'}" within Nuxt itself. Please avoid naming your composable the same as a preset to prevent unexpected behavior.`)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e87f6d3 and 0540391.

📒 Files selected for processing (1)
  • packages/nuxt/src/imports/module.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: build
packages/nuxt/src/imports/module.ts

[failure] 131-131:
Argument of type 'InlinePreset | PresetImport' is not assignable to parameter of type 'string'.


[failure] 133-133:
Property 'as' does not exist on type 'ImportPresetWithDeprecation'.


[failure] 133-133:
Argument of type 'string' is not assignable to parameter of type 'ImportPresetWithDeprecation[][]'.


[failure] 137-137:
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

🔇 Additional comments (2)
packages/nuxt/src/imports/module.ts (2)

128-129: ⚠️ Potential issue

Correct property access on preset.

The property as does not exist on type ImportPresetWithDeprecation, leading to a TypeScript error. You might need to use an existing property like from or name.

Apply this diff to fix the property access:

-  presetMap.set(preset.as, preset.from)
+  presetMap.set(preset.from, preset.from)

Likely invalid or redundant comment.


121-121: ⚠️ Potential issue

Fix the TypeScript type definition for presetMap.

The current type definition new Map<string, typeof presets[]>() is invalid TypeScript syntax. Using typeof presets[] is incorrect. You should specify the correct type for the map values based on what you're storing.

Apply this diff to correct the type definition:

-const presetMap = new Map<string, typeof presets[]>()
+const presetMap = new Map<string, string>()

Likely invalid or redundant comment.

packages/nuxt/src/imports/module.ts Outdated Show resolved Hide resolved
packages/nuxt/src/imports/module.ts Outdated Show resolved Hide resolved
packages/nuxt/src/imports/module.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (2)
packages/nuxt/src/imports/module.ts (2)

132-137: LGTM! Clear and helpful warning message

The warning implementation effectively alerts developers about naming conflicts between their composables and preset imports. The message includes all necessary details: the conflicting name, the preset source, and the file location.

Consider adding a link to documentation about naming best practices:

- console.warn(`[imports] "${name}" is already defined and auto imported from "${preset ?? 'unknown preset'}" within nuxt itself. Please consider renaming "${name}" at ${i.from}.`)
+ console.warn(`[imports] "${name}" is already defined and auto imported from "${preset ?? 'unknown preset'}" within nuxt itself. Please consider renaming "${name}" at ${i.from}. See: https://nuxt.com/docs/guide/directory-structure/composables`)
🧰 Tools
🪛 GitHub Check: build

[failure] 133-133:
Property 'as' does not exist on type 'ImportPresetWithDeprecation'.


[failure] 133-133:
Argument of type 'string' is not assignable to parameter of type 'ImportPresetWithDeprecation[][]'.


120-138: Implementation successfully meets PR objectives

The code effectively implements the warning system for preset import overrides as requested in issue #29258. The implementation:

  1. Tracks preset imports efficiently using a Map
  2. Provides clear warnings with actionable information
  3. Handles edge cases appropriately

Note: As mentioned in the PR description, this doesn't cover all cases (e.g., imports from pages/module.ts), but it's a solid first step.

For future improvements:

  1. Consider extracting the warning logic into a separate function for better testability
  2. Add configuration options to customize or disable these warnings
  3. Extend the coverage to handle imports from additional locations
🧰 Tools
🪛 GitHub Check: build

[failure] 131-131:
Argument of type 'InlinePreset | PresetImport' is not assignable to parameter of type 'string'.


[failure] 133-133:
Property 'as' does not exist on type 'ImportPresetWithDeprecation'.


[failure] 133-133:
Argument of type 'string' is not assignable to parameter of type 'ImportPresetWithDeprecation[][]'.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0540391 and 06add6e.

📒 Files selected for processing (1)
  • packages/nuxt/src/imports/module.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: build
packages/nuxt/src/imports/module.ts

[failure] 131-131:
Argument of type 'InlinePreset | PresetImport' is not assignable to parameter of type 'string'.


[failure] 133-133:
Property 'as' does not exist on type 'ImportPresetWithDeprecation'.


[failure] 133-133:
Argument of type 'string' is not assignable to parameter of type 'ImportPresetWithDeprecation[][]'.

packages/nuxt/src/imports/module.ts Outdated Show resolved Hide resolved
Comment on lines +124 to +128
preset.imports = preset.imports ?? []
for (const i of preset.imports) {
presetMap.set(i, preset.from)
}
presetMap.set(preset.as, preset.from)
Copy link
Contributor Author

@OrbisK OrbisK Nov 19, 2024

Choose a reason for hiding this comment

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

the previous implementation has type issues. types are weired on the presets. I tried to solve it like this, but seems kinda hacky

Suggested change
preset.imports = preset.imports ?? []
for (const i of preset.imports) {
presetMap.set(i, preset.from)
}
presetMap.set(preset.as, preset.from)
for (const i of preset.imports) {
if(typeof i === "string") {
presetMap.set(i, preset.from)
continue
}
let name, as, from
if(Array.isArray(i)) {
[name, as, from] = i
}
else {
name = ('name' in i) ? i.name : undefined
as = ('as' in i) ? i.as : undefined
from = preset.from
}
if(!name || !from) {
continue
}
presetMap.set(as ?? name, from)
}

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 06add6e and 38bfe2a.

📒 Files selected for processing (1)
  • packages/nuxt/src/imports/module.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: build
packages/nuxt/src/imports/module.ts

[failure] 131-131:
Argument of type 'InlinePreset | PresetImport' is not assignable to parameter of type 'string'.


[failure] 133-133:
Property 'as' does not exist on type 'ImportPresetWithDeprecation'.

Comment on lines +132 to +137
const name = i.as ?? i.name
const preset = presetMap.get(name)

if (preset) {
console.warn(`[imports] "${name}" is already defined and auto imported from "${preset ?? 'unknown preset'}" within nuxt itself. Please consider renaming "${name}" at ${i.from}.`)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance the warning implementation.

While the warning implementation works, it could be improved for better developer experience and code consistency:

  1. Use the Nuxt logger utility for consistent warning format
  2. Enhance code structure with early returns
  3. Make the warning message more actionable

Apply this diff to implement these improvements:

-const name = i.as ?? i.name
-const preset = presetMap.get(name)
-
-if (preset) {
-  console.warn(`[imports] "${name}" is already defined and auto imported from "${preset ?? 'unknown preset'}" within nuxt itself. Please consider renaming "${name}" at ${i.from}.`)
-}
+const importName = i.as ?? i.name
+const presetSource = presetMap.get(importName)
+if (!presetSource) {
+  continue
+}
+
+logger.warn(
+  `Import conflict: "${importName}" is already auto-imported from preset "${presetSource}"\n` +
+  `  Source: ${i.from}\n` +
+  `  Solution: Consider renaming the import or using a different name via 'as' syntax`
+)

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: build

[failure] 133-133:
Property 'as' does not exist on type 'ImportPresetWithDeprecation'.

packages/nuxt/src/imports/module.ts Show resolved Hide resolved
Copy link
Member

@danielroe danielroe left a comment

Choose a reason for hiding this comment

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

I think what we want is:

  • not to warn if using an import from a layer
  • only warn if overriding with an equal priority - this way modules can intentionally override without warnings

@OrbisK
Copy link
Contributor Author

OrbisK commented Dec 25, 2024

I think what we want is:

  • not to warn if using an import from a layer
  • only warn if overriding with an equal priority - this way modules can intentionally override without warnings

I can try. This shouldn't be possible in src/imports/module, should it?

Any advise?

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

Successfully merging this pull request may close these issues.

2 participants