Skip to content

chore: add eslint rules to enact import rules #4760

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 1 commit into
base: develop
Choose a base branch
from

Conversation

straker
Copy link
Contributor

@straker straker commented Apr 28, 2025

Adds eslint rules to restrict import paths from #4758, as well as virtual node use in utils.

@straker straker requested a review from a team as a code owner April 28, 2025 20:42
Copy link

coderabbitai bot commented Apr 28, 2025

Walkthrough

This update introduces stricter ESLint rules to enforce architectural boundaries regarding import patterns across the codebase. Several files have been refactored to source their dependencies from internal modules instead of external packages, aligning with the new linting constraints. The ESLint ignore list is also refined to target a specific file rather than a broader pattern. No changes are made to exported or public entities; all modifications are limited to configuration and import statements.

Changes

File(s) Change Summary
eslint.config.js Extended ESLint rules to enforce strict import boundaries and usage constraints across various directories; refined ESLint ignore list.
lib/commons/text/has-unicode.js
lib/commons/text/remove-unicode.js
Changed import of emojiRegexText from external 'emoji-regex' to named import from internal '../../core/imports'.
lib/core/base/audit.js Changed import of doT from external '@deque/dot' to named import from internal '../imports'.
lib/core/utils/css-parser.js Changed import of CssSelectorParser from external 'css-selector-parser' to internal '../imports'.
lib/core/utils/memoize.js Changed import of memoize from external 'memoizee' to named import from internal '../imports'.

Sequence Diagram(s)

sequenceDiagram
    participant File as Source File (e.g., utils, commons, base)
    participant Imports as Internal Imports Module
    participant External as External Package

    File->>Imports: import { dependency } from '../imports'
    Imports->>External: (internally sources dependency)
    File-->>File: Uses dependency as before
Loading

This diagram illustrates the new import flow, where source files now import dependencies from a centralized internal module, which in turn manages access to external packages. This enforces stricter boundaries and centralized control over third-party dependencies.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

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

♻️ Duplicate comments (5)
eslint.config.js (5)

162-187: Same pattern object issue as above

The regex key is repeated here; please update to group (or convert to plain pattern strings) to ensure the rule actually runs.


188-212: Repeated mis-configuration (regex key) – fix required


213-230: Repeated mis-configuration (regex key) – fix required


231-253: Repeated mis-configuration (regex key) – fix required


255-276: Repeated mis-configuration (regex key) – fix required

🧹 Nitpick comments (1)
eslint.config.js (1)

368-369: Duplicate ignore entry for lib/core/imports/polyfills.js

polyfills.js is already whitelisted in the dedicated polyfill block (lines 317-321).
Keeping the duplicate in the global ignore list is harmless but clutters the config.

-      'lib/core/imports/polyfills.js',
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 344c65b and 7e7c733.

📒 Files selected for processing (6)
  • eslint.config.js (2 hunks)
  • lib/commons/text/has-unicode.js (1 hunks)
  • lib/commons/text/remove-unicode.js (1 hunks)
  • lib/core/base/audit.js (1 hunks)
  • lib/core/utils/css-parser.js (1 hunks)
  • lib/core/utils/memoize.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Security Review
🔇 Additional comments (5)
lib/commons/text/remove-unicode.js (1)

7-7: Good import refactoring to follow architectural boundaries

The import for emojiRegexText has been updated to use the centralized imports module instead of directly importing from an external package. This aligns with the new ESLint rules and improves architectural consistency.

lib/commons/text/has-unicode.js (1)

7-7: Consistent import path update

The import for emojiRegexText has been correctly updated to use the internal imports module, matching the same pattern applied in other files. This ensures consistent dependency management and complies with the new ESLint rules.

lib/core/utils/css-parser.js (1)

1-1: Import refactored to use centralized imports module

The import for CssSelectorParser has been updated to use the internal imports module instead of directly importing from an external package. This change aligns with the PR objectives and follows the same pattern as other import updates.

lib/core/utils/memoize.js (1)

1-1: Import path updated to follow architectural pattern

The import for memoize has been properly updated to use the internal imports module, which centralizes external dependencies. This helps enforce the architectural boundaries specified in the new ESLint rules.

eslint.config.js (1)

277-300: Virtual-node ban looks good – legacy exceptions documented

The explicit allow-list for the four legacy files plus the generic ban elsewhere is clear and will prevent future regressions.

Comment on lines +14 to 15
import { doT } from '../imports';
import constants from '../constants';
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Confirm doT is (named) re-exported from lib/core/imports

The original code consumed the default export from @deque/dot.
After the refactor we import a named symbol:

import { doT } from '../imports';

If lib/core/imports/index.js (or the resolved file) does not re-export doT with the same structure ({ compile() { … } }) every runtime call to doT.compile(...) (e.g. lines 605, 637, 657, 671) will explode with “compile is not a function”.

Run the quick check below – if nothing is printed the symbol is missing or not exported as named:

If no lines are reported, we need either:

-import { doT } from '../imports';
+import doT from '../imports';

or we must add export const doT = … into lib/core/imports.


🏁 Script executed:

#!/usr/bin/env bash
# Verify that a named export `doT` exists under lib/core/imports
fd --extension js 'lib/core/imports' -x \
  node - <<'PY'
import importlib.util, sys, pathlib, inspect, json, os
target = pathlib.Path('lib/core/imports')
for p in target.rglob('*.js'):
    mod_name = p.stem
    # crude static detection – look for `export.*doT`
    with open(p) as f:
        src = f.read()
    if 'export' in src and 'doT' in src:
        print(f"Found possible doT export in {p}")
PY

Length of output: 416


Let’s correct the search and look for any doT exports under lib/core/imports:


🏁 Script executed:

#!/usr/bin/env bash
# Search for named or default exports of doT in lib/core/imports
fd --extension js . lib/core/imports -x grep -Hn "export .*doT" {}
fd --extension js . lib/core/imports -x grep -Hn "export default .*doT" {}

Length of output: 149


Ensure doT Is Actually Exported from lib/core/imports

I ran a check across lib/core/imports and found no evidence of either a named or default export for doT. As written, this line in lib/core/base/audit.js will fail at runtime:

import { doT } from '../imports';

Please address one of the following:

• Add a named export in your imports entry point (lib/core/imports/index.js or equivalent):

// lib/core/imports/index.js
import doT from '@deque/dot';
export const doT = doT;

• Or switch back to a default import and ensure you export default in the imports module:

// lib/core/base/audit.js
- import { doT } from '../imports';
+ import doT from '../imports';

Either way, confirm that doT.compile(...) calls will resolve correctly.

🤖 Prompt for AI Agents (early access)
In lib/core/base/audit.js around lines 14 to 15, the import statement for doT uses a named import from '../imports', but doT is not currently exported as a named export in lib/core/imports. To fix this, update the exports in lib/core/imports/index.js (or the main imports file) to include a named export for doT by importing doT from '@deque/dot' and then exporting it as a named export. Alternatively, revert to a default import for doT and ensure the imports module exports doT as default. This will ensure that calls to doT.compile(...) in audit.js work correctly at runtime.

Comment on lines +125 to +141
{
// disallow imports from node modules
ignores: ['lib/core/imports/**/*.js'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
regex: '^[^.]',
message: 'Only core/imports files should import from node modules'
}
]
}
]
}
},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

no-restricted-imports mis-configured – regex is not a supported key

patterns expects an array of strings or objects with a group field (see ESLint docs).
Objects of the form:

{
  regex: '^[^.]',
  message: '…'
}

are silently ignored, so the new restriction will never fire.

A minimal fix:

-          patterns: [
-            {
-              regex: '^[^.]',
-              message: 'Only core/imports files should import from node modules'
-            }
-          ]
+          patterns: [
+            {
+              group: ['^[^.]'],   // or simply '*'  if you want all non-relative paths
+              message: 'Only core/imports files should import from node modules'
+            }
+          ]

The same regex objects appear in multiple rule blocks (utils, public, reporters, commons, etc. ‑ see lines 163-276). Please adjust those as well, otherwise the lint step will pass but provide no protection.

🤖 Prompt for AI Agents (early access)
In eslint.config.js from lines 125 to 141, the no-restricted-imports rule incorrectly uses a regex key inside patterns, which ESLint does not support. Replace the regex key with a group key containing the regex string to properly enforce the restriction. Also, locate and update all similar occurrences of this misconfiguration in other rule blocks between lines 163 and 276 to ensure consistent linting behavior.

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