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: refactor with typescript to support esm and cjs both #51

Closed
wants to merge 4 commits into from

Conversation

liuhanqu
Copy link

@liuhanqu liuhanqu commented Nov 20, 2023

BREAKING CHANGE: Drop Node.js < 16 support

  1. 使用 ts 重构
  2. 使用 tshy 支持 esm 和 cjs
  3. test 使用 test-runner (这里需要 node v18 版本)

Summary by CodeRabbit

  • New Features

    • Introduced waitPort function for asynchronously waiting for port availability.
    • Added comprehensive test cases for CLI tools and port detection.
  • Updates

    • Updated Node.js versions in workflows to include the latest versions.
    • Enhanced detectPort function with improved parameter handling and versatility.
  • Bug Fixes

    • None specified.
  • Chores

    • Updated .gitignore to exclude .tshy* files and dist/ directory.
    • Updated dependencies and scripts in package.json.
    • Configured ESLint for improved code quality and consistency.
  • Refactor

    • Migrated to ES6 import syntax for better module management.

@fengmk2 fengmk2 self-requested a review November 20, 2023 12:30
@fengmk2 fengmk2 self-assigned this Nov 20, 2023
@fengmk2
Copy link
Member

fengmk2 commented Nov 20, 2023

https://github.com/node-modules/detect-port/blob/master/.github/workflows/nodejs.yml#L18 这里去掉 14,加上 20 的测试环境

@liuhanqu
Copy link
Author

想问下 waitPort 方法的使用场景是什么?
看了代码,没太 get 到

Copy link

coderabbitai bot commented May 29, 2024

Walkthrough

The recent updates enhance the project's configuration, dependencies, and functionality. ESLint rules are refined, Node.js versions in workflows are updated, and the .gitignore file is expanded. Key scripts now use ES6 syntax, and the detectPort function is more versatile. New test files ensure robust validation for CLI tools and port detection. These changes collectively improve code quality, compatibility, and functionality.

Changes

File(s) Change Summary
.eslintrc Introduced TypeScript rules, node prefix conventions, and disabled TypeScript comment ban rule.
.github/workflows/nodejs.yml Updated Node.js versions from '14, 16, 18' to '16, 18, 20'.
.gitignore Added exclusions for .tshy* files and dist/ directory.
bin/detect-port.ts Transitioned to ES6 import syntax and updated port detection logic.
package.json Modified main entry, updated dependencies, added new scripts, and introduced new configurations.
src/detect-port.ts Enhanced detectPort function with multiple overloads and new type definitions.
src/index.ts Added imports and exports for detectPort and waitPort.
src/wait-port.ts Introduced waitPort function for asynchronously waiting for port availability.
test/cli.test.ts Added test cases for CLI tool related to port detection.
test/detect-port.test.ts Introduced tests for port detection functionality under various scenarios.
test/wait-port.test.ts Added test cases for waitPort function.
tsconfig.json Extended configuration from @eggjs/tsconfig and set compiler options for target, module, and moduleResolution.

Poem

In code's vast fields, changes bloom,
ESLint rules and ports resume.
Node.js versions climb the tree,
Testing ports with glee.
Scripts now in ES6's light,
Dependencies set just right.
A rabbit hops with joy to see,
A project thriving, wild and free. 🌸🐇


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@fengmk2
Copy link
Member

fengmk2 commented May 29, 2024

想问下 waitPort 方法的使用场景是什么? 看了代码,没太 get 到

一直在尝试等待指定端口可用。

@fengmk2
Copy link
Member

fengmk2 commented May 29, 2024

我重新基于你的分支 rebase 一下.

@fengmk2 fengmk2 closed this May 29, 2024
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: 13

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 5e8f3ed and ffe6468.
Files selected for processing (12)
  • .eslintrc (1 hunks)
  • .github/workflows/nodejs.yml (1 hunks)
  • .gitignore (1 hunks)
  • bin/detect-port.ts (3 hunks)
  • package.json (2 hunks)
  • src/detect-port.ts (5 hunks)
  • src/index.ts (1 hunks)
  • src/wait-port.ts (1 hunks)
  • test/cli.test.ts (1 hunks)
  • test/detect-port.test.ts (1 hunks)
  • test/wait-port.test.ts (1 hunks)
  • tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (5)
  • .eslintrc
  • .github/workflows/nodejs.yml
  • .gitignore
  • src/index.ts
  • tsconfig.json
Additional Context Used
Biome (29)
bin/detect-port.ts (2)

24-24: Use Number.parseInt instead of the equivalent global.


42-42: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

src/detect-port.ts (15)

49-49: Unexpected any. Specify a different type.


64-64: Unexpected any. Specify a different type.


94-94: Unexpected any. Specify a different type.


112-112: Unexpected any. Specify a different type.


119-119: Unexpected any. Specify a different type.


24-24: Reassigning a function parameter is confusing.


28-28: Reassigning a function parameter is confusing.


32-32: Reassigning a function parameter is confusing.


23-23: Reassigning a function parameter is confusing.


27-27: Reassigning a function parameter is confusing.


32-32: Use Number.parseInt instead of the equivalent global.


51-51: Reassigning a function parameter is confusing.


54-54: Reassigning a function parameter is confusing.


55-55: Reassigning a function parameter is confusing.


128-128: Reassigning a function parameter is confusing.

src/wait-port.ts (3)

21-21: Unexpected any. Specify a different type.


22-22: Unexpected any. Specify a different type.


14-14: Use Number.Infinity instead of the equivalent global.

test/cli.test.ts (3)

49-49: Template literals are preferred over string concatenation.


43-43: Use Number.parseInt instead of the equivalent global.


50-50: Use Number.parseInt instead of the equivalent global.

test/detect-port.test.ts (4)

51-51: Prefer for...of instead of forEach.


84-84: Unexpected any. Specify a different type.


90-90: Unexpected any. Specify a different type.


103-103: Template literals are preferred over string concatenation.

test/wait-port.test.ts (2)

11-11: Prefer for...of instead of forEach.


28-28: Unexpected any. Specify a different type.

Additional comments not posted (1)
bin/detect-port.ts (1)

Line range hint 42-42: Replace isNaN with Number.isNaN for safer type checking.
[REFACTOR_SUGGESTion]

- } else if (isNaN(port)) {
+ } else if (Number.isNaN(port)) {

t.mock.reset();
});

it('work with listening next port 4001 because 4000 was listened to ' + ip(), async () => {
Copy link

Choose a reason for hiding this comment

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

Use template literals for string operations to enhance readability and maintainability.

- it('work with listening next port 4001 because 4000 was listened to ' + ip(), async () => {
+ it(`work with listening next port 4001 because 4000 was listened to ${ip()}`, async () => {

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.

Suggested change
it('work with listening next port 4001 because 4000 was listened to ' + ip(), async () => {
it(`work with listening next port 4001 because 4000 was listened to ${ip()}`, async () => {

}
});
after(() => {
servers.forEach(server => server.close());
Copy link

Choose a reason for hiding this comment

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

Consider using for...of instead of forEach for better readability and performance in modern JavaScript.

- servers.forEach(server => server.close());
+ for (const server of servers) {
+   server.close();
+ }

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.

Suggested change
servers.forEach(server => server.close());
for (const server of servers) {
server.close();
}

});

it('should listen next port 4001 when localhost is not binding', async t => {
t.mock.method(dns, 'lookup', (address: string, callback: (...args: any[]) => void) => {
Copy link

Choose a reason for hiding this comment

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

Refine type definitions to avoid using any.

- t.mock.method(dns, 'lookup', (address: string, callback: (...args: any[]) => void) => {
+ t.mock.method(dns, 'lookup', (address: string, callback: (...args: unknown[]) => void) => {
- const err = new Error(`getaddrinfo ENOTFOUND ${address}`);
- (err as any).code = 'ENOTFOUND';
+ const err: NodeJS.ErrnoException = new Error(`getaddrinfo ENOTFOUND ${address}`);
+ err.code = 'ENOTFOUND';

Also applies to: 90-90


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.

Suggested change
t.mock.method(dns, 'lookup', (address: string, callback: (...args: any[]) => void) => {
t.mock.method(dns, 'lookup', (address: string, callback: (...args: unknown[]) => void) => {
const err: NodeJS.ErrnoException = new Error(`getaddrinfo ENOTFOUND ${address}`);
err.code = 'ENOTFOUND';

try {
const port = 9093;
await waitPort(port, { retries: 3, retryInterval: 100 });
} catch (err:any) {
Copy link

Choose a reason for hiding this comment

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

Specify a more precise type than any for error handling.

- } catch (err:any) {
+ } catch (err: Error) {

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.

Suggested change
} catch (err:any) {
} catch (err: Error) {

describe('wait for port', () => {
const servers: net.Server[] = [];
after(() => {
servers.forEach(server => server.close());
Copy link

Choose a reason for hiding this comment

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

Consider using a for...of loop for better readability and performance.

- servers.forEach(server => server.close());
+ for (const server of servers) {
+   server.close();
+ }

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.

Suggested change
servers.forEach(server => server.close());
for (const server of servers) {
server.close();
}

@@ -10,7 +10,7 @@
"detect": "./bin/detect-port.js",
"detect-port": "./bin/detect-port.js"
},
"main": "index.js",
"main": "./dist/commonjs/index.js",
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The output indicates that the build scripts in package.json do not explicitly mention generating the ./dist/commonjs/index.js file. This suggests that the build process might not be correctly configured to produce the expected output file.

  • The prepublishOnly script runs tsc, tshy, and tshy-after, but none of these commands explicitly mention generating the ./dist/commonjs/index.js file.
  • The tsc script compiles ./bin/detect-port.ts, which does not align with the expected output path.

To resolve this, you should ensure that the build process correctly generates the ./dist/commonjs/index.js file. This might involve updating the TypeScript configuration or the build scripts.

Analysis chain

Ensure the "main" entry points to the correct compiled output.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the main entry points to the correct compiled output.

# Test: Check if the main entry exists.
test -f ./dist/commonjs/index.js

Length of output: 34



Script:

#!/bin/bash
# Description: Verify if the build scripts in package.json are configured to generate the expected output file.

# Extract the build scripts from package.json
jq '.scripts' package.json

# Check if the expected output file is mentioned in the build configurations
grep -r './dist/commonjs/index.js' .

Length of output: 539


it('should output available port randomly', { only: true }, async () => {
const res = await execaNodeWithLoader(binFile);
const port = parseInt(stripAnsi(res.stdout).trim(), 10);
Copy link

Choose a reason for hiding this comment

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

Use Number.parseInt instead of parseInt to avoid using the global function.

- const port = parseInt(stripAnsi(res.stdout).trim(), 10);
+ const port = Number.parseInt(stripAnsi(res.stdout).trim(), 10);

Also applies to: 50-50


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.

Suggested change
const port = parseInt(stripAnsi(res.stdout).trim(), 10);
const port = Number.parseInt(stripAnsi(res.stdout).trim(), 10);


it('should output available port from the given port', async () => {
const givenPort = 9000;
const res = await execaNodeWithLoader(binFile, [ givenPort + '' ]);
Copy link

Choose a reason for hiding this comment

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

Prefer template literals over string concatenation for better readability and potential performance benefits.

- const res = await execaNodeWithLoader(binFile, [ givenPort + '' ]);
+ const res = await execaNodeWithLoader(binFile, [`$givenPort`]);

Committable suggestion was skipped due low confidence.

@@ -50,7 +61,7 @@ function tryListen(port, maxPort, hostname, callback) {
if (hostname) {
listen(port, hostname, (err, realPort) => {
if (err) {
if (err.code === 'EADDRNOTAVAIL') {
if ((err as any).code === 'EADDRNOTAVAIL') {
Copy link

Choose a reason for hiding this comment

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

Specify a more precise type than any for error handling.

- if ((err as any).code === 'EADDRNOTAVAIL') {
+ if ((err as NodeJS.ErrnoException).code === 'EADDRNOTAVAIL') {

Also applies to: 94-94, 119-119


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.

Suggested change
if ((err as any).code === 'EADDRNOTAVAIL') {
if ((err as NodeJS.ErrnoException).code === 'EADDRNOTAVAIL') {

export default function detectPort(port?: number | string | PortConfig | DetectPortCallback, callback?: DetectPortCallback) {
let hostname: string | undefined = '';

if (port && typeof port === 'object') {
Copy link

Choose a reason for hiding this comment

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

Avoid reassigning function parameters as it can lead to unexpected behavior and makes the code harder to understand.

- port = parseInt(port as unknown as string) || 0;
+ const parsedPort = Number.parseInt(port as unknown as string) || 0;

Also applies to: 28-28, 32-32, 23-23, 27-27, 32-32, 51-51, 54-54, 55-55, 128-128


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.

Suggested change
if (port && typeof port === 'object') {
if (port && typeof port === 'object') {
const parsedPort = Number.parseInt(port as unknown as string) || 0;

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.

None yet

2 participants