Skip to content

chore: remove unnecessary tslib by targeting ES2021#11

Merged
JounQin merged 1 commit intomainfrom
chore/cleanup
Apr 20, 2025
Merged

chore: remove unnecessary tslib by targeting ES2021#11
JounQin merged 1 commit intomainfrom
chore/cleanup

Conversation

@JounQin
Copy link
Member

@JounQin JounQin commented Apr 20, 2025

Summary by CodeRabbit

  • Refactor

    • Modernized import statements for Node.js core modules to use namespace imports throughout the codebase.
    • Replaced legacy TypeScript helper usage with direct imports and native async/await syntax.
    • Simplified error handling and assignment patterns using more concise modern JavaScript syntax.
  • Chores

    • Removed the dependency on tslib from the project.
    • Updated TypeScript and ESLint configuration options for improved compatibility and code style consistency.

@JounQin JounQin requested a review from Copilot April 20, 2025 13:09
@coderabbitai
Copy link

coderabbitai bot commented Apr 20, 2025

Walkthrough

This set of changes removes the tslib dependency from the project, refactors all imports of Node.js core modules to use direct require or namespace import syntax, and updates the TypeScript configuration to disallow synthetic default imports and ES module interop. The codebase is modernized by using native async/await, concise nullish coalescing, and optional chaining. No public APIs or exported entity signatures are changed, except for two internal functions that are now native async. The ESLint configuration is also updated to disable the unicorn/import-style rule.

Changes

File(s) Change Summary
package.json Removed the tslib dependency from the dependencies section.
tsconfig.json Added "allowSyntheticDefaultImports": false, "esModuleInterop": false, and set "target": "ES2021".
eslint.config.mjs Disabled the unicorn/import-style rule in ESLint configuration.
lib/constants.js, src/constants.ts Replaced tslib and default imports of path with direct require (JS) or namespace import (TS).
lib/helpers.js, src/helpers.ts Removed tslib imports for fs and path, replaced with direct require or namespace imports; updated type annotations for compatibility; simplified error handling and nullish checks.
lib/index.js, src/index.ts Replaced all tslib and default imports of Node.js modules (fs, https, path, zlib) with direct require or namespace imports; modernized async/await usage in JS.
lib/target.js Simplified nullish coalescing assignments for platform and architecture mapping using ??.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant checkAndPreparePackage (index.js)
    participant installUsingNPM
    participant downloadDirectlyFromNPM
    participant fs/path modules

    User->>checkAndPreparePackage: Call with package info
    checkAndPreparePackage->>fs/path modules: Attempt to resolve native binding
    alt Binding not found
        checkAndPreparePackage->>installUsingNPM: Try install via npm
        alt installUsingNPM fails
            checkAndPreparePackage->>downloadDirectlyFromNPM: Download tarball directly
        end
    end
    checkAndPreparePackage-->>User: Return result or error
Loading

Possibly related issues

  • chore: drop tslib dependency x-fetch#27: The main issue's changes to remove tslib imports and replace them with direct Node.js core module imports directly correspond to the retrieved issue's goal of dropping the tslib dependency.

Poem

🐇✨
Farewell to tslib, we hop on ahead,
With native imports, our worries have fled.
No more default tricks, just namespace delight,
Our code is now cleaner, and future-proofed right.
With ESLint in line and TypeScript in tow,
This rabbit’s code garden continues to grow!
🌱💻

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

eslint.config.mjs

Oops! Something went wrong! :(

ESLint: 9.25.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@1stg/eslint-config' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

lib/target.js

Oops! Something went wrong! :(

ESLint: 9.25.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@1stg/eslint-config' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

lib/constants.js

Oops! Something went wrong! :(

ESLint: 9.25.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@1stg/eslint-config' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

  • 5 others
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR removes the unnecessary tslib dependency by converting module imports and refactoring the code to target ES2021. Key changes include:

  • Updating import statements in multiple files (e.g. src/index.ts, src/helpers.ts, lib/constants.js) to use native Node.js module syntax.
  • Replacing tslib‑based helper functions with modern JavaScript features like nullish coalescing.
  • Minor refactoring in asynchronous functions and error message formatting for consistency.

Reviewed Changes

Copilot reviewed 14 out of 15 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/index.ts Updated import style for Node.js built-ins to use namespace imports.
src/helpers.ts Changed import and type annotation for fs to use namespace pattern.
src/constants.ts Adjusted import for path to use namespace imports.
lib/target.js Refactored to use nullish coalescing operators for clarity.
lib/index.js Removed tslib dependency and updated async/await patterns accordingly.
lib/helpers.js Converted tslib‑based imports to native require statements.
lib/constants.js Updated import for path and removed tslib usage.
eslint.config.mjs Disabled the unicorn/import-style rule to accommodate updated syntax.
Files not reviewed (1)
  • package.json: Language not supported

@codecov
Copy link

codecov bot commented Apr 20, 2025

Codecov Report

Attention: Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.

Project coverage is 39.56%. Comparing base (63eaac2) to head (4557d5d).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/helpers.ts 66.66% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main      #11   +/-   ##
=======================================
  Coverage   39.56%   39.56%           
=======================================
  Files           6        6           
  Lines         460      460           
  Branches       53       53           
=======================================
  Hits          182      182           
  Misses        278      278           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions
Copy link
Contributor

size-limit report 📦

Path Size
lib/index.js 2.04 KB (-6.24% 🔽)

@pkg-pr-new
Copy link

pkg-pr-new bot commented Apr 20, 2025

Open in StackBlitz

npm i https://pkg.pr.new/napi-postinstall@11

commit: 4557d5d

@github-actions
Copy link
Contributor

📊 Package size report   -4.74%↓

File Before After
lib/constants.js 567 B -14.3%↓486 B
lib/constants.js.map 307 B -0.33%↓306 B
lib/helpers.js 7.8 kB -9.58%↓7.1 kB
lib/helpers.js.map 6.4 kB -2.97%↓6.2 kB
lib/index.js 7.2 kB -12.2%↓6.3 kB
lib/index.js.map 5.9 kB -1.33%↓5.8 kB
lib/target.js 1.5 kB -6%↓1.4 kB
lib/target.js.map 1.5 kB -0.89%↓1.4 kB
package.json 3.5 kB -1.34%↓3.5 kB
Total (Includes all files) 44.8 kB -4.74%↓42.7 kB
Tarball size 12.9 kB -3.55%↓12.4 kB
Unchanged files
File Size
lib/cli.d.ts 31 B
lib/cli.js 289 B
lib/cli.js.map 282 B
lib/constants.d.ts 168 B
lib/helpers.d.ts 685 B
lib/index.d.ts 249 B
lib/target.d.ts 348 B
lib/types.d.ts 541 B
lib/types.js 110 B
lib/types.js.map 102 B
LICENSE 1.1 kB
README.md 6.3 kB

🤖 This report was automatically generated by pkg-size-action

@github-actions
Copy link
Contributor

Deploy preview for napi-postinstall ready!

✅ Preview
https://napi-postinstall-5a4xvobmx-1stg.vercel.app

Built with commit 4557d5d.
This pull request is being automatically deployed with vercel-action

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

🔭 Outside diff range comments (1)
lib/index.js (1)

12-28: 🛠️ Refactor suggestion

Guard against infinite or excessive HTTP redirects

fetch() recursively follows 301/302 responses but does not cap redirect depth or handle status codes such as 303/307/308.
A malicious registry endpoint could create an endless chain and exhaust the call stack.

Consider adding a maxRedirects parameter:

-function fetch(url) {
+function fetch(url, maxRedirects = 8) {
     return new Promise((resolve, reject) => {
         https
             .get(url, res => {
-            if ((res.statusCode === 301 || res.statusCode === 302) &&
-                res.headers.location) {
-                fetch(res.headers.location).then(resolve, reject);
+            if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {
+                if (maxRedirects === 0) {
+                    return reject(new Error('Too many HTTP redirects'));
+                }
+                fetch(res.headers.location, maxRedirects - 1).then(resolve, reject);
                 return;
             }
🧹 Nitpick comments (3)
lib/helpers.js (2)

26-44: Replace deprecated fs.rmdirSync with fs.rmSync

fs.rmdirSync (without the recursive flag) has been deprecated since Node 14 and removed in Node 18.
Using the modern counterpart ensures forward‑compatibility:

-    fs.rmdirSync(dir);
+    // `force` handles readonly files, `recursive` removes children.
+    fs.rmSync(dir, { recursive: true, force: true });

98-103: Tiny optimisation: avoid reading the entire ldd binary

fs.readFileSync('/usr/bin/ldd', 'utf8') loads the whole executable into memory just to check for the string “musl”.
Using fs.readFileSync without encoding and scanning only the first few KB, or running ldd --version, would be lighter. Not critical, but worth considering for constrained environments.

lib/index.js (1)

88-97: Ensure target directory exists before fs.writeFileSync

downloadedNodePath() returns a path within the host package’s lib directory, but there is no guarantee that this directory exists on disk (e.g. if the package was just created).
Adding fs.mkdirSync(path.dirname(nodePath), { recursive: true }) before the write makes the function more robust.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 63eaac2 and 4557d5d.

⛔ Files ignored due to path filters (5)
  • lib/constants.js.map is excluded by !**/*.map
  • lib/helpers.js.map is excluded by !**/*.map
  • lib/index.js.map is excluded by !**/*.map
  • lib/target.js.map is excluded by !**/*.map
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • eslint.config.mjs (1 hunks)
  • lib/constants.js (1 hunks)
  • lib/helpers.js (5 hunks)
  • lib/index.js (3 hunks)
  • lib/target.js (1 hunks)
  • package.json (0 hunks)
  • src/constants.ts (1 hunks)
  • src/helpers.ts (2 hunks)
  • src/index.ts (1 hunks)
  • tsconfig.json (1 hunks)
💤 Files with no reviewable changes (1)
  • package.json
🧰 Additional context used
🧬 Code Graph Analysis (3)
lib/constants.js (3)
lib/index.js (1)
  • path (7-7)
lib/helpers.js (1)
  • path (12-12)
src/constants.ts (1)
  • require (7-9)
src/helpers.ts (1)
lib/helpers.js (2)
  • stats (29-29)
  • fs (11-11)
lib/helpers.js (1)
src/helpers.ts (3)
  • removeRecursive (20-36)
  • downloadedNodePath (38-41)
  • getNapiInfoFromPackageJson (51-105)
🪛 GitHub Check: codecov/patch
src/helpers.ts

[warning] 23-23: src/helpers.ts#L23
Added line #L23 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
🔇 Additional comments (11)
eslint.config.mjs (1)

13-13: Good change for supporting the new import style

Disabling the unicorn/import-style rule allows for consistent use of namespace imports (import * as fs) throughout the codebase, aligning with the updated TypeScript configuration that disables synthetic default imports.

tsconfig.json (2)

4-5: Well-executed TypeScript configuration update

Setting both allowSyntheticDefaultImports and esModuleInterop to false correctly enforces the use of namespace imports for CommonJS modules, which aligns with the goal of removing tslib dependency and using more accurate import patterns.


10-10: Good choice of target

Setting the target to ES2021 is appropriate as it natively supports features like async/await, nullish coalescing, and optional chaining, eliminating the need for TypeScript to generate helper functions via tslib.

src/constants.ts (1)

1-1: Correct import style update

Changing to namespace import syntax (import * as path) is appropriate since Node.js core modules don't have a default export in the CommonJS module system. This aligns with the TypeScript configuration changes.

src/index.ts (1)

4-7: Consistent import style changes

Switching to namespace imports for all Node.js core modules is the correct approach given the updated TypeScript configuration. These changes properly align with the goal of removing dependency on tslib for synthetic default imports.

src/helpers.ts (2)

2-3: Appropriate namespace import conversion

Changing to namespace imports for Node.js core modules aligns with the TypeScript configuration updates and ensures consistency across the codebase.


23-23: Correctly updated type reference

The type annotation was properly updated to use the type from the namespace import (fs.Stats instead of the previously imported Stats type).

The static analysis tool flagged this line as not covered by tests, but this is just a type annotation that has no runtime impact. No action needed.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 23-23: src/helpers.ts#L23
Added line #L23 was not covered by tests

lib/target.js (1)

45-46: Nullish coalescing succinctly improves readability – looks good

Switching from the previous verbose fallback logic to ?? is correct and compatible with your ES 2021 target. No functional change is introduced, and the intent is clearer.

lib/constants.js (1)

5-7: Direct require("node:path") import and package.json resolution are fine

The simplified import pattern eliminates the need for tslib helpers and keeps the code consistent with other files. The synchronous require(path.resolve(...)) call is also acceptable here because it runs exactly once at module load time.

lib/helpers.js (1)

220-222: Nice concise fallback in getErrorMessage

Using optional chaining keeps the helper minimal and robust.

lib/index.js (1)

104-107: Version consistency check is spot‑on

Good call verifying that the “host” and binary packages share the same version number when checkVersion is requested.

@JounQin JounQin merged commit 365b82a into main Apr 20, 2025
30 checks passed
@JounQin JounQin deleted the chore/cleanup branch April 20, 2025 13:20
@JounQin JounQin restored the chore/cleanup branch April 20, 2025 13:21
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.

2 participants