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

fix: try to use index.* when package.json not exists #32

Merged
merged 1 commit into from
Dec 28, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 28, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new export extend in both CommonJS and TypeScript modules, allowing access to a boolean value of true.
  • Bug Fixes

    • Improved handling of the pkg variable in the module resolution process.
  • Tests

    • Added new test cases for verifying module resolution and imports for the extend modules in CommonJS and TypeScript contexts.

Copy link

vercel bot commented Dec 28, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
egg-utils ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 28, 2024 2:16am

Copy link

coderabbitai bot commented Dec 28, 2024

Walkthrough

The pull request introduces modifications to the module resolution process in src/import.ts, focusing on improving the handling of the pkg variable in the tryToResolveByDirname function. Additionally, new test cases are added to verify module resolution for CommonJS and TypeScript modules, specifically testing the extend modules. The changes ensure consistent variable declaration and enhance test coverage for import functionality.

Changes

File Change Summary
src/import.ts Modified tryToResolveByDirname function to declare pkg as an empty object at the beginning of the function
test/fixtures/cjs/extend/index.js Added new export exports.extend = true
test/fixtures/ts-module/extend/index.ts Added new exported constant const extend = true
test/import.test.ts Added new test cases for importResolve() and importModule() to verify module path resolution and importing for extend modules

Possibly related PRs

Poem

🐰 Resolving modules with grace and might,
A rabbit's code takes a leap of delight!
pkg now dances, free and bold,
Imports and tests, a story untold.
Code hops forward, with extend in 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

pkg-pr-new bot commented Dec 28, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/utils/@eggjs/utils@32

commit: b0358f4

Copy link

codecov bot commented Dec 28, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.46%. Comparing base (7caad4d) to head (b0358f4).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #32      +/-   ##
==========================================
+ Coverage   89.44%   89.46%   +0.01%     
==========================================
  Files           6        6              
  Lines         616      617       +1     
  Branches      104      104              
==========================================
+ Hits          551      552       +1     
  Misses         65       65              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 814a85c and b0358f4.

📒 Files selected for processing (4)
  • src/import.ts (1 hunks)
  • test/fixtures/cjs/extend/index.js (1 hunks)
  • test/fixtures/ts-module/extend/index.ts (1 hunks)
  • test/import.test.ts (3 hunks)
✅ Files skipped from review due to trivial changes (2)
  • test/fixtures/ts-module/extend/index.ts
  • test/fixtures/cjs/extend/index.js
🔇 Additional comments (4)
test/import.test.ts (4)

12-12: Good addition to verify the resolution for cjs/extend.

This new assertion adds clarity to confirm that importResolve correctly resolves the cjs/extend path.


33-33: Ensures TypeScript extension resolution is tested.

Similarly, this line checks the TypeScript extend path, strengthening the test coverage.


56-59: Tests correctness of imported extend object in CJS.

Confirming the extend property is set to true ensures the import works as expected.


61-64: Verifies TS import under importDefaultOnly option.

This assertion effectively ensures that TypeScript modules also expose the extend property when only the default is imported.

Comment on lines +145 to +150
let pkg: any = {};
const pkgFile = path.join(dirname, 'package.json');
if (fs.existsSync(pkgFile)) {
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
return tryToResolveByDirnameFromPackage(dirname, pkg);
pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
}
return tryToResolveByDirnameFromPackage(dirname, pkg);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use safer JSON parsing or add error handling.

Currently, the code directly reads and parses package.json, which can throw an error if the file is malformed or has unexpected content. To make it more robust, consider wrapping the parse operation in a try/catch block and handling errors gracefully.

 function tryToResolveByDirname(dirname: string): string | undefined {
   let pkg: any = {};
   const pkgFile = path.join(dirname, 'package.json');
   if (fs.existsSync(pkgFile)) {
+    try {
       pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
+    } catch (err) {
+      debug('[tryToResolveByDirname] failed to parse package.json at %o: %o', pkgFile, err);
+    }
   }
   return tryToResolveByDirnameFromPackage(dirname, pkg);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let pkg: any = {};
const pkgFile = path.join(dirname, 'package.json');
if (fs.existsSync(pkgFile)) {
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
return tryToResolveByDirnameFromPackage(dirname, pkg);
pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
}
return tryToResolveByDirnameFromPackage(dirname, pkg);
let pkg: any = {};
const pkgFile = path.join(dirname, 'package.json');
if (fs.existsSync(pkgFile)) {
try {
pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
} catch (err) {
debug('[tryToResolveByDirname] failed to parse package.json at %o: %o', pkgFile, err);
}
}
return tryToResolveByDirnameFromPackage(dirname, pkg);

@fengmk2 fengmk2 merged commit b4b2e0c into master Dec 28, 2024
25 checks passed
@fengmk2 fengmk2 deleted the import-with-no-packagejson branch December 28, 2024 02:21
fengmk2 pushed a commit that referenced this pull request Dec 28, 2024
[skip ci]

## [4.1.6](v4.1.5...v4.1.6) (2024-12-28)

### Bug Fixes

* try to use index.* when package.json not exists ([#32](#32)) ([b4b2e0c](b4b2e0c))
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