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: ignore js file when the same ts file exists #280

Merged
merged 1 commit into from
Dec 29, 2024
Merged

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 29, 2024

Summary by CodeRabbit

  • New Features

    • Added TypeScript support for Egg.js framework
    • Introduced a new TypeScript example project with basic routing and configuration
  • Bug Fixes

    • Improved file loading logic to prevent conflicts between .js and .ts files
  • Chores

    • Updated package scripts for testing and continuous integration
    • Added ESLint and TypeScript configuration files
    • Updated dependencies to support TypeScript development
  • Tests

    • Added comprehensive test suite for TypeScript project
    • Implemented test cases for route handling and application behavior

Copy link

coderabbitai bot commented Dec 29, 2024

Walkthrough

The pull request introduces comprehensive TypeScript support for the Egg.js framework by adding a new TypeScript-based test fixture project helloworld-ts. This includes creating configuration files like .eslintrc, tsconfig.json, and package.json, along with sample application files in both JavaScript and TypeScript. The changes modify the file loading mechanism to prioritize TypeScript files over JavaScript files and update the core package's scripts to support TypeScript testing and development workflows.

Changes

File Change Summary
package.json - Modified test script to use egg-bin test
- Added posttest and postci scripts to run npm run clean
src/loader/file_loader.ts - Updated debug logging string
- Added conditional check to ignore .js files when corresponding .ts files exist
test/fixtures/helloworld-ts/ - Added multiple configuration and application files for TypeScript support
- Included .eslintrc, .gitignore, package.json, tsconfig.json
- Created sample controller, router, and config files in .js and .ts
test/support-typescript.test.ts - New test file to verify TypeScript file loading and application behavior

Sequence Diagram

sequenceDiagram
    participant FL as FileLoader
    participant TS as TypeScript File
    participant JS as JavaScript File
    
    FL->>TS: Check for .ts file
    alt .ts file exists
        FL->>JS: Ignore .js file
        FL-->>TS: Load TypeScript file
    else No .ts file
        FL-->>JS: Load JavaScript file
    end
Loading

Poem

🐰 A Rabbit's TypeScript Tale 🔧

In Egg.js land, where code takes flight,
TypeScript dances with pure delight
Ignoring .js with graceful ease
Compiling magic that truly please
A framework hopping, clean and bright! 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 29, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/core/@eggjs/core@280

commit: 0dac399

Copy link

New dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@eggjs/mock@6.0.1 environment Transitive: eval, filesystem +113 4.73 MB fengmk2
npm/@types/node@22.10.2 None +1 2.37 MB types
npm/egg@4.0.0-beta.11 Transitive: environment, eval, filesystem, network +142 16.2 MB fengmk2

View full report↗︎

Copy link

codecov bot commented Dec 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.86%. Comparing base (0f0a13c) to head (0dac399).
Report is 2 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #280   +/-   ##
=======================================
  Coverage   97.86%   97.86%           
=======================================
  Files          10       10           
  Lines        3366     3373    +7     
  Branches      591      594    +3     
=======================================
+ Hits         3294     3301    +7     
  Misses         72       72           

☔ 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

🧹 Nitpick comments (5)
test/fixtures/helloworld-ts/config/config.default.js (1)

1-1: Remove redundant "use strict" directive

The "use strict" directive is redundant in ES modules as they are automatically in strict mode.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/helloworld-ts/app/router.js (1)

1-1: Remove the redundant 'use strict' directive.
Modules automatically run in strict mode in modern JS environments, making this directive unnecessary.

Apply the following diff:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/helloworld-ts/app/controller/foo.js (1)

1-1: Remove redundant 'use strict' directive.

JavaScript modules are automatically executed in strict mode, making the 'use strict' directive unnecessary.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

src/loader/file_loader.ts (1)

188-194: Ignore .js when .ts exists: validate side-effects.

Automatically skipping the .js file if a corresponding .ts file is found aligns with TypeScript-first logic. However, be mindful of potential edge cases where only a .d.ts file is present, or where the .js file may be necessary for other reasons. Consider logging a warning if ignoring .js might introduce unexpected runtime behaviors.

package.json (1)

18-18: Consider removing redundant test-local script

Both test and test-local scripts now use the same command egg-bin test. This duplication might cause confusion. Consider removing the test-local script if it's no longer serving a different purpose.

  "scripts": {
    "test": "egg-bin test",
    "posttest": "npm run clean",
-   "test-local": "egg-bin test",
    "preci": "npm run clean && npm run lint && npm run prepublishOnly",

Also applies to: 21-21

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a7c9e4e and 0dac399.

📒 Files selected for processing (14)
  • package.json (1 hunks)
  • src/loader/file_loader.ts (2 hunks)
  • test/fixtures/helloworld-ts/.eslintrc (1 hunks)
  • test/fixtures/helloworld-ts/.gitignore (1 hunks)
  • test/fixtures/helloworld-ts/app/controller/foo.js (1 hunks)
  • test/fixtures/helloworld-ts/app/controller/foo.ts (1 hunks)
  • test/fixtures/helloworld-ts/app/router.js (1 hunks)
  • test/fixtures/helloworld-ts/app/router.ts (1 hunks)
  • test/fixtures/helloworld-ts/config/config.default.js (1 hunks)
  • test/fixtures/helloworld-ts/config/config.default.ts (1 hunks)
  • test/fixtures/helloworld-ts/package.json (1 hunks)
  • test/fixtures/helloworld-ts/test/index.test.ts (1 hunks)
  • test/fixtures/helloworld-ts/tsconfig.json (1 hunks)
  • test/support-typescript.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • test/fixtures/helloworld-ts/config/config.default.ts
  • test/fixtures/helloworld-ts/.gitignore
  • test/fixtures/helloworld-ts/.eslintrc
  • test/fixtures/helloworld-ts/tsconfig.json
🧰 Additional context used
🪛 Biome (1.9.4)
test/fixtures/helloworld-ts/app/router.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/helloworld-ts/app/controller/foo.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/helloworld-ts/config/config.default.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (12)
test/fixtures/helloworld-ts/config/config.default.js (1)

1-5: ⚠️ Potential issue

Remove this JS file since a TS version exists

According to the PR objective to "ignore js file when the same ts file exists", this JavaScript file should be removed since there's an identical TypeScript version at config/config.default.ts. Having both files maintained in parallel could lead to synchronization issues.

Let's verify the existence and content of the TypeScript version:

✅ Verification successful

Remove the redundant JavaScript config file

The TypeScript version of config.default.ts exists and contains identical configuration. As per the PR's objective to ignore JS files when corresponding TS files exist, this JavaScript file should be removed to avoid maintenance overhead and potential synchronization issues.

  • test/fixtures/helloworld-ts/config/config.default.js should be deleted as it's redundant with test/fixtures/helloworld-ts/config/config.default.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the TS file exists and compare contents
if [ -f "test/fixtures/helloworld-ts/config/config.default.ts" ]; then
    echo "TypeScript version exists. Comparing contents:"
    diff <(cat test/fixtures/helloworld-ts/config/config.default.js) <(cat test/fixtures/helloworld-ts/config/config.default.ts)
else
    echo "TypeScript version not found"
fi

Length of output: 405


Script:

#!/bin/bash
# Let's verify if the TS file exists first
fd "config.default.ts" test/fixtures/helloworld-ts/

# If it exists, let's see its content
if [ -f "test/fixtures/helloworld-ts/config/config.default.ts" ]; then
    echo "Content of TS file:"
    cat test/fixtures/helloworld-ts/config/config.default.ts
fi

# Let's also check if there are any other config files in this directory
echo -e "\nAll config files in the directory:"
fd "config" test/fixtures/helloworld-ts/config/

Length of output: 563

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/helloworld-ts/app/router.ts (1)

1-5: Looks good for a basic route setup.
You have a straightforward configuration for the root path. Everything appears correct and consistent.

test/fixtures/helloworld-ts/app/router.js (1)

3-7: Approved route logic.
The route logic matches the TypeScript counterpart.

test/fixtures/helloworld-ts/test/index.test.ts (2)

1-9: Tests for the root path look good.
They provide complete coverage for the "Hello World" scenario.


11-18: Validate that /foo behaves as expected in TypeScript.
Currently, the test checks the JavaScript controller. If the TypeScript controller is intended to deliver the same response, ensure the render method has a parallel implementation.

test/support-typescript.test.ts (1)

1-22: Looks good.

This new test file cleanly demonstrates the intended behavior of ignoring the .js file when a .ts file is present. The test case is straightforward, and the use of supertest for HTTP assertions is appropriate. Consider adding coverage for edge cases (such as when no .ts file exists) if needed by other requirements.

test/fixtures/helloworld-ts/app/controller/foo.js (1)

3-11: Controller logic looks sound, but verify context injection.

The controller references this.ctx, which is typically set by the Egg.js framework. Confirm that the context is properly injected in all relevant scenarios. If no injection is configured for this code path, errors may occur due to this.ctx being undefined.

src/loader/file_loader.ts (1)

9-9: Updated debug log message style is fine.

Switching from @eggjs/core:file_loader to @eggjs/core/file_loader is acceptable and more consistent with typical naming styles. No issues found.

test/fixtures/helloworld-ts/package.json (2)

4-5: Confirm stability of "egg" at version "beta".

Depending on your release cycle, you might prefer a pinned stable version to avoid unexpected breaking changes. Verify that this particular beta version is suitable for production or fully tested in your environment.


16-26: Script definitions appear comprehensive.

Scripts cover development, testing, linting, and build steps. Validate that these commands align with your CI/CD flow and do not introduce duplications. For instance, you might unify the lint steps under one lifecycle script if that better suits your project’s pipeline organization.

package.json (2)

19-19: LGTM! Clean post-hooks implementation

The addition of posttest and postci scripts ensures consistent cleanup after test and CI runs. This is a good practice for maintaining a clean state between test runs.

Also applies to: 23-23


Line range hint 1-108: Verify the main PR implementation

While these package.json changes support TypeScript integration, the main PR objective of ignoring JS files when equivalent TS files exist should be implemented elsewhere in the codebase.

Let's verify where this logic is implemented:

✅ Verification successful

Let's search more specifically for the implementation:


Found the TypeScript precedence implementation

The main PR objective of ignoring JS files when equivalent TS files exist is implemented in src/loader/file_loader.ts. The implementation includes:

  1. TypeScript file detection:
files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions['.ts'])
  ? [ '**/*.(js|ts)', '!**/*.d.ts' ]
  : [ '**/*.js' ];
  1. JS file skipping when TS exists:
if (filepath.endsWith('.js')) {
  const filepathTs = filepath.replace(/\.js$/, '.ts');
  if (filepaths.includes(filepathTs)) {
    debug('[parse] ignore %s, because %s exists', fullpath, filepathTs);
    continue;
  }
}

Let's verify the utils extension configuration:


Implementation verified and complete

The PR's main objective of ignoring JS files when equivalent TS files exist is properly implemented in src/loader/file_loader.ts. The implementation consists of two main parts:

  1. File pattern selection based on TypeScript environment:
files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions['.ts'])
  ? [ '**/*.(js|ts)', '!**/*.d.ts' ]
  : [ '**/*.js' ];
  1. JS file skipping logic when TS exists:
if (filepath.endsWith('.js')) {
  const filepathTs = filepath.replace(/\.js$/, '.ts');
  if (filepaths.includes(filepathTs)) {
    debug('[parse] ignore %s, because %s exists', fullpath, filepathTs);
    continue;
  }
}

The implementation uses Node.js's native module extensions (accessed via utils.extensions) and environment variable EGG_TYPESCRIPT to control TypeScript support, ensuring JS files are properly ignored when equivalent TS files exist.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential file loading/extension handling logic
rg -g '!*.{json,md}' -l "\.ts|\.js" 

# Search for specific loader or file resolution logic
ast-grep --pattern 'function $_($$_) {
  $$$
  /\.ts|\.js/
  $$$
}'

Length of output: 1985


Script:

#!/bin/bash
# Search for file loader implementation that might handle extension precedence
rg -A 10 "\.ts|\.js" src/loader/file_loader.ts

# Look for any extension handling in the loader
rg -A 10 "extensions?" src/loader/file_loader.ts

# Check for any TypeScript-specific loading logic
rg -A 10 "typescript|\.ts" src/loader/file_loader.ts

Length of output: 4950


Script:

#!/bin/bash
# Check the utils extension configuration
rg -A 5 "extensions.*\.ts" src/utils/index.ts

Length of output: 47


Script:

#!/bin/bash
# Let's try a broader search for extensions configuration
rg -A 5 "extensions" src/utils/index.ts

# Also check if it's exported from another file
rg -l "export.*extensions" src/

# Look for any TypeScript-related configuration
rg -A 5 "typescript|EGG_TYPESCRIPT" src/utils/

Length of output: 615

Comment on lines +2 to +3
async render() {
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider providing an implementation for the render method.
Currently, the method body is empty, which may cause failing tests or unimplemented features if it's intended to mirror the JavaScript version that sets a 400 status and returns { foo: 'bar' }.

Do you want me to propose an implementation here and align it with the JavaScript counterpart?

@fengmk2 fengmk2 merged commit a6acc88 into master Dec 29, 2024
23 checks passed
@fengmk2 fengmk2 deleted the ignore-ts branch December 29, 2024 08:28
fengmk2 pushed a commit that referenced this pull request Dec 29, 2024
[skip ci]

## [6.2.6](v6.2.5...v6.2.6) (2024-12-29)

### Bug Fixes

* ignore js file when the same ts file exists ([#280](#280)) ([a6acc88](a6acc88))
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