Skip to content

fix(scripts): use file URL for ESM sourcemap preload - #6044

Open
gxkl wants to merge 1 commit into
nextfrom
codex/fix-scripts-windows-import-url
Open

fix(scripts): use file URL for ESM sourcemap preload#6044
gxkl wants to merge 1 commit into
nextfrom
codex/fix-scripts-windows-import-url

Conversation

@gxkl

@gxkl gxkl commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Motivation

On Windows, egg-scripts passes the resolved source-map-support path directly to Node.js --import for ESM applications. A drive-letter path such as D:\app\node_modules\source-map-support\register.js is parsed as the unsupported d: URL scheme, causing ERR_UNSUPPORTED_ESM_URL_SCHEME during production startup.

Fixes #6041.

Changes

  • convert the internally resolved source-map-support path to a file URL before passing it to --import
  • keep the CommonJS --require path unchanged
  • add regression coverage for an ESM application with egg.typescript enabled

Testing

  • cd tools/scripts && ut run test -- test/start-unit.test.ts (3 passed)
  • cd tools/scripts && ut run test (24 passed, 38 skipped)
  • cd tools/scripts && ut run typecheck
  • oxfmt --check on the changed files
  • git diff --check

Summary by CodeRabbit

  • Bug Fixes
    • Fixed startup for ESM TypeScript applications by ensuring source maps load correctly.
    • ESM applications now launch with the appropriate module format and file URL configuration.
    • CommonJS startup behavior remains unchanged.

Copilot AI lite review requested due to automatic review settings August 5, 2026 10:02
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: add9d0e0-dbdb-4b07-9fdb-3800fb4bdc1e

📥 Commits

Reviewing files that changed from the base of the PR and between 2b18475 and 0cf8ac6.

📒 Files selected for processing (2)
  • tools/scripts/src/commands/start.ts
  • tools/scripts/test/start-unit.test.ts

📝 Walkthrough

Walkthrough

The start command converts ESM source-map support paths to file URLs. Tests cover ESM cluster script selection and verify the file: preload URL.

Changes

ESM startup handling

Layer / File(s) Summary
ESM startup path and validation
tools/scripts/src/commands/start.ts, tools/scripts/test/start-unit.test.ts
The start command passes a file URL to Node’s ESM --import option. Tests select .mjs for ESM applications and verify the file: URL. CommonJS continues to use the filesystem path with --require.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the ESM sourcemap preload fix and matches the primary change.
Linked Issues check ✅ Passed The changes use pathToFileURL() for ESM --import, preserve CommonJS behavior, and add regression coverage for the Windows startup failure in issue #6041.
Out of Scope Changes check ✅ Passed All changes are limited to the start command and its regression test, which directly support issue #6041.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-scripts-windows-import-url

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

Comment @coderabbitai help to get the list of available commands.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 5, 2026

Copy link
Copy Markdown

Deploying egg with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0cf8ac6
Status: ✅  Deploy successful!
Preview URL: https://04c41274.egg-cci.pages.dev
Branch Preview URL: https://codex-fix-scripts-windows-im.egg-cci.pages.dev

View logs

@codecov

codecov Bot commented Aug 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 83.10%. Comparing base (2b18475) to head (0cf8ac6).

Additional details and impacted files
@@            Coverage Diff             @@
##             next    #6044      +/-   ##
==========================================
+ Coverage   83.08%   83.10%   +0.02%     
==========================================
  Files         730      730              
  Lines       22474    22474              
  Branches     4520     4520              
==========================================
+ Hits        18673    18678       +5     
+ Misses       3297     3293       -4     
+ Partials      504      503       -1     

☔ View full report in Codecov by Harness.
📢 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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 fixes Windows production startup for ESM apps when egg.typescript enables sourcemaps by ensuring the source-map-support/register.js preload passed to Node’s --import is a file:// URL (avoiding drive-letter paths being parsed as an unsupported URL scheme).

Changes:

  • Convert the resolved source-map-support/register.js path to a file:// URL when using --import for ESM apps.
  • Keep the CommonJS preload path unchanged via --require.
  • Add a regression unit test covering an ESM app ("type": "module") with egg.typescript: true.

Reviewed changes

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

File Description
tools/scripts/src/commands/start.ts Uses pathToFileURL(...).href when pushing the ESM --import preload for source-map-support.
tools/scripts/test/start-unit.test.ts Adds a regression test asserting ESM startup uses --import file: and adjusts the stubbed server bin to return .mjs for ESM.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 5, 2026

Copy link
Copy Markdown

Deploying egg-v3 with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0cf8ac6
Status: ✅  Deploy successful!
Preview URL: https://1a1633bc.egg-v3.pages.dev
Branch Preview URL: https://codex-fix-scripts-windows-im.egg-v3.pages.dev

View logs

Copilot AI review requested due to automatic review settings August 7, 2026 03:57
@gxkl
gxkl force-pushed the codex/fix-scripts-windows-import-url branch from 2674193 to d231d0b Compare August 7, 2026 03:57
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings August 7, 2026 06:42
@gxkl
gxkl force-pushed the codex/fix-scripts-windows-import-url branch from d231d0b to 8cbfc88 Compare August 7, 2026 06:42
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@gxkl
gxkl requested review from elrrrrrrr, fengmk2 and killagu August 7, 2026 06:46

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
tools/scripts/test/start-unit.test.ts (1)

23-23: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise Start.getServerBin() for ESM resolution.

TestStart.getServerBin() overrides Start.getServerBin() and returns the mjs/cjs extension from the override. The ESM test at tools/scripts/test/start-unit.test.ts:92 only checks that double. Delegate to super.getServerBin() here or add a direct test on Start.getServerBin().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/scripts/test/start-unit.test.ts` at line 23, Update
TestStart.getServerBin() so the ESM test exercises Start.getServerBin() rather
than bypassing it with a hardcoded extension; delegate to the superclass
implementation while preserving the test fixture’s fake script path behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tools/scripts/test/start-unit.test.ts`:
- Around line 72-99: Extend the ESM preload test around TestStart.run to
explicitly exercise a Windows drive-style esmBaseDir, independent of the host
platform. Verify that the generated --import argument is a file URL with the
Windows path correctly converted, while preserving the existing POSIX-platform
coverage.

---

Nitpick comments:
In `@tools/scripts/test/start-unit.test.ts`:
- Line 23: Update TestStart.getServerBin() so the ESM test exercises
Start.getServerBin() rather than bypassing it with a hardcoded extension;
delegate to the superclass implementation while preserving the test fixture’s
fake script path behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a8de3ba-9689-46a3-b5af-b0f2880dea93

📥 Commits

Reviewing files that changed from the base of the PR and between 3a3bc65 and 8cbfc88.

📒 Files selected for processing (2)
  • tools/scripts/src/commands/start.ts
  • tools/scripts/test/start-unit.test.ts

Comment on lines +72 to +99
it('preloads source-map-support with a file URL for ESM apps', async () => {
const esmBaseDir = path.join(homeDir, 'esm-typescript-app');
await fs.mkdir(esmBaseDir);
await fs.writeFile(
path.join(esmBaseDir, 'package.json'),
JSON.stringify({ name: 'esm-typescript-app', type: 'module', egg: { typescript: true } }),
);
spawnMock.mockImplementation(() => ({
once: vi.fn().mockReturnThis(),
on: vi.fn().mockReturnThis(),
unref: vi.fn(),
disconnect: vi.fn(),
kill: vi.fn(),
pid: 1112,
}));

await TestStart.run(['--workers=1', esmBaseDir]);

expect(spawnMock).toHaveBeenCalledTimes(1);
const [, args] = spawnMock.mock.calls[0] as [string, string[]];
expect(args).toContain('/fake/scripts/start-cluster.mjs');
const importIndex = args.indexOf('--import');
expect(importIndex).toBeGreaterThan(-1);
// A Windows drive path such as D:\app\register.js is parsed as the
// unsupported `d:` URL scheme by Node's ESM loader unless it is a file URL.
expect(args[importIndex + 1]).toMatch(/^file:/);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 3 'windows-(latest|2022|2025)|runs-on:.*windows|matrix.*(os|platform)|start-unit\.test' .

Repository: eggjs/egg

Length of output: 1888


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "## workflow files"
fd -a '.*\.(yml|yaml)$' .github/workflows 2>/dev/null | sed 's#^\./##' | sort | while read -r f; do
  echo "--- $f"
  rg -n -C 3 'runs-on|windows-latest|matrix|isCI|isWindowsCI|vitest|start-unit|npm test|scripts' "$f" || true
done

echo "## vitest config"
cat -n vitest.config.ts | sed -n '1,120p'

echo "## test relevant section"
cat -n tools/scripts/test/start-unit.test.ts | sed -n '60,110p'

echo "## package scripts"
python3 - <<'PY'
import json, pathlib
p=pathlib.Path('package.json')
if p.exists():
    for k,v in json.loads(p.read_text()).get('scripts',{}).items():
        if 'vitest' in k.lower() or 'test' in k.lower().split('-')[-1]:
            print(f"{k}: {v}")
PY

Repository: eggjs/egg

Length of output: 21057


Add explicit Windows path coverage for ESM preload URLs.

Run CI on windows-latest includes tools/scripts/test/start-unit.test.ts, but esmBaseDir is built with the current platform. A POSIX CI runner still sees POSIX paths. Add a Windows-path cover case or a platform-factory path input so --import URL creation covers Windows drive paths.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] 74-77: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.writeFile(
path.join(esmBaseDir, 'package.json'),
JSON.stringify({ name: 'esm-typescript-app', type: 'module', egg: { typescript: true } }),
)
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/scripts/test/start-unit.test.ts` around lines 72 - 99, Extend the ESM
preload test around TestStart.run to explicitly exercise a Windows drive-style
esmBaseDir, independent of the host platform. Verify that the generated --import
argument is a file URL with the Windows path correctly converted, while
preserving the existing POSIX-platform coverage.

Copilot AI review requested due to automatic review settings August 7, 2026 07:13
@gxkl
gxkl force-pushed the codex/fix-scripts-windows-import-url branch from 8cbfc88 to 0cf8ac6 Compare August 7, 2026 07:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

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.

【Bug】Windows 下 eggctl start 启动失败,@eggjs/scripts --import 未转换为 file:// URL 导致 ERR_UNSUPPORTED_ESM_URL_SCHEME

2 participants