Skip to content

Commit a4f7410

Browse files
gxklkillagu
andauthored
fix(scripts): use file URL for ESM sourcemap preload (#6044)
## 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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved source-map loading when starting applications in ESM mode, including when the application path contains spaces or special characters. CommonJS preload behavior remains unchanged. * **Tests** * Added Windows coverage for ESM and CommonJS startup, including source-map preloading and foreground child-process exits. Windows tests run on Node.js 24; existing Linux coverage across Node.js versions remains in place. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: killagu <killa07071201@gmail.com>
1 parent a65dcd7 commit a4f7410

6 files changed

Lines changed: 93 additions & 26 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,9 @@ jobs:
395395
node: '24'
396396
coverage: false
397397
include:
398+
- os: 'windows-latest'
399+
node: '24'
400+
coverage: false
398401
- os: 'ubuntu-latest'
399402
node: '24'
400403
coverage: true
@@ -449,18 +452,23 @@ jobs:
449452

450453
# own step for clear failure attribution; @eggjs/scripts has no build
451454
# script of its own, so build it through the root tsdown workspace
452-
# filter (path form is fine here, this job only runs on ubuntu)
455+
# filter. Windows runs only source-level regression tests and needs no build.
453456
- name: Build egg-scripts
457+
if: ${{ matrix.os != 'windows-latest' }}
454458
run: ut run build -- --workspace ./tools/scripts
455459

456460
- name: Run tests (with coverage)
457461
if: ${{ matrix.coverage }}
458462
run: ut run ci --workspace @eggjs/scripts
459463

460464
- name: Run tests
461-
if: ${{ !matrix.coverage }}
465+
if: ${{ !matrix.coverage && matrix.os != 'windows-latest' }}
462466
run: ut run test --workspace @eggjs/scripts
463467

468+
- name: Run Windows preload and foreground exit regression tests
469+
if: ${{ matrix.os == 'windows-latest' }}
470+
run: ut run test --workspace @eggjs/scripts -- test/start-unit.test.ts
471+
464472
- name: Code Coverage
465473
if: ${{ matrix.coverage }}
466474
uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5.5.5

‎tools/scripts/src/commands/start.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { mkdir, rename, stat, open, type FileHandle } from 'node:fs/promises';
33
import os from 'node:os';
44
import path from 'node:path';
55
import { scheduler } from 'node:timers/promises';
6+
import { pathToFileURL } from 'node:url';
67
import { debuglog, promisify } from 'node:util';
78

89
import { getFrameworkPath, importResolve } from '@eggjs/utils';
@@ -309,7 +310,7 @@ export default class Start<T extends typeof Start> extends BaseCommand<T> {
309310
});
310311
const sourceMapSupport = path.join(path.dirname(sourceMapSupportPkgPath), 'register.js');
311312
if (this.isESM) {
312-
execArgv.push('--import', sourceMapSupport);
313+
execArgv.push('--import', pathToFileURL(sourceMapSupport).href);
313314
} else {
314315
execArgv.push('--require', sourceMapSupport);
315316
}

‎tools/scripts/test/start-unit.test.ts‎

Lines changed: 65 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
1+
import { execFile } from 'node:child_process';
12
import { fstatSync } from 'node:fs';
23
import fs from 'node:fs/promises';
4+
import { createRequire } from 'node:module';
35
import os from 'node:os';
46
import path from 'node:path';
7+
import { pathToFileURL } from 'node:url';
8+
import { promisify } from 'node:util';
59

10+
import { importResolve } from '@eggjs/utils';
611
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
712

813
import Start from '../src/commands/start.ts';
914

1015
const spawnMock = vi.hoisted(() => vi.fn());
1116

17+
vi.mock('@eggjs/utils', async (importOriginal) => {
18+
const actual = await importOriginal<typeof import('@eggjs/utils')>();
19+
return { ...actual, importResolve: vi.fn(actual.importResolve) };
20+
});
21+
1222
vi.mock('node:child_process', async (importOriginal) => {
1323
const actual = await importOriginal<typeof import('node:child_process')>();
1424
return { ...actual, spawn: spawnMock };
@@ -21,7 +31,7 @@ class TestStart extends (Start as any) {
2131
return '/fake/framework';
2232
}
2333
async getServerBin() {
24-
return '/fake/scripts/start-cluster.cjs';
34+
return `/fake/scripts/start-cluster.${this.isESM ? 'mjs' : 'cjs'}`;
2535
}
2636
}
2737

@@ -48,19 +58,17 @@ describe('test/start-unit.test.ts', () => {
4858

4959
// foreground mode waits for the child inside run(), so tests must report a
5060
// child exit for the command to settle
51-
async function runStartWithChildExit(code: number | null, signal: NodeJS.Signals | null): Promise<void> {
52-
let onExit: ((code: number | null, signal: NodeJS.Signals | null) => void) | undefined;
61+
async function runStartWithChildExit(
62+
code: number | null,
63+
signal: NodeJS.Signals | null,
64+
appDir = baseDir,
65+
): Promise<void> {
5366
spawnMock.mockImplementation(() => ({
5467
once: vi.fn((event: string, cb: (code: number | null, signal: NodeJS.Signals | null) => void) => {
55-
if (event === 'exit') onExit = cb;
68+
if (event === 'exit') queueMicrotask(() => cb(code, signal));
5669
}),
5770
}));
58-
const run = TestStart.run(['--workers=1', baseDir]);
59-
await vi.waitFor(() => {
60-
if (!onExit) throw new Error('child not spawned yet');
61-
});
62-
onExit!(code, signal);
63-
return run;
71+
return TestStart.run(['--workers=1', appDir]);
6472
}
6573

6674
it('cluster mode spawns the start-cluster server bin with cluster options', async () => {
@@ -78,6 +86,48 @@ describe('test/start-unit.test.ts', () => {
7886
expect(options.env.NODE_ENV).toBe('production');
7987
});
8088

89+
it.each(['module', 'commonjs'])('preloads source-map-support for %s apps and exits', async (type) => {
90+
const appDir = path.join(homeDir, `${type}-typescript-app`);
91+
await fs.mkdir(appDir);
92+
await fs.writeFile(
93+
path.join(appDir, 'package.json'),
94+
JSON.stringify({ name: `${type}-typescript-app`, type, egg: { typescript: true } }),
95+
);
96+
const require = createRequire(import.meta.url);
97+
const originalPackage = require.resolve('source-map-support/package.json');
98+
const supportDir = path.join(homeDir, 'source map # support');
99+
await fs.cp(path.dirname(originalPackage), supportDir, { recursive: true });
100+
// Resolve the copied package's dependencies through the original installation.
101+
await fs.symlink(
102+
path.join(path.dirname(originalPackage), '../'),
103+
path.join(supportDir, 'node_modules'),
104+
'junction',
105+
);
106+
vi.mocked(importResolve).mockReturnValue(path.join(supportDir, 'package.json'));
107+
108+
await runStartWithChildExit(0, null, appDir);
109+
110+
expect(spawnMock).toHaveBeenCalledTimes(1);
111+
const [, args] = spawnMock.mock.calls[0] as [string, string[]];
112+
const esm = type === 'module';
113+
expect(args).toContain(`/fake/scripts/start-cluster.${esm ? 'mjs' : 'cjs'}`);
114+
const preloadFlag = esm ? '--import' : '--require';
115+
const preloadIndex = args.indexOf(preloadFlag);
116+
expect(preloadIndex).toBeGreaterThan(-1);
117+
const register = path.join(supportDir, 'register.js');
118+
expect(args[preloadIndex + 1]).toBe(esm ? pathToFileURL(register).href : register);
119+
expect(args).not.toContain(esm ? '--require' : '--import');
120+
if (esm) expect(args[preloadIndex + 1]).toContain('source%20map%20%23%20support');
121+
const { stdout } = await promisify(execFile)(process.execPath, [
122+
preloadFlag,
123+
args[preloadIndex + 1],
124+
'--input-type=module',
125+
'--eval',
126+
'console.log(typeof Error.prepareStackTrace)',
127+
]);
128+
expect(stdout.trim()).toBe('function');
129+
});
130+
81131
it('daemon mode backgrounds once the child reports egg-ready over IPC', async () => {
82132
const unref = vi.fn();
83133
const disconnect = vi.fn();
@@ -134,20 +184,14 @@ describe('test/start-unit.test.ts', () => {
134184
});
135185

136186
it('foreground mode rejects when the child fails to spawn', async () => {
137-
let onError: ((err: Error) => void) | undefined;
187+
// A nonexistent --node executable emits 'error' and may never emit 'exit'.
188+
const spawnError = new Error('spawn ENOENT');
138189
spawnMock.mockImplementation(() => ({
139190
once: vi.fn((event: string, cb: (err: Error) => void) => {
140-
if (event === 'error') onError = cb;
191+
if (event === 'error') queueMicrotask(() => cb(spawnError));
141192
}),
142193
}));
143-
const run = TestStart.run(['--workers=1', baseDir]);
144-
await vi.waitFor(() => {
145-
if (!onError) throw new Error('child not spawned yet');
146-
});
147-
// e.g. a nonexistent --node executable: 'error' fires and 'exit' never does
148-
const spawnError = new Error('spawn ENOENT');
149-
onError!(spawnError);
150-
// the raw child error is rethrown as-is, not wrapped
151-
await expect(run).rejects.toBe(spawnError);
194+
// The raw child error is rethrown as-is, not wrapped.
195+
await expect(TestStart.run(['--workers=1', baseDir])).rejects.toBe(spawnError);
152196
});
153197
});

‎wiki/index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Read this file before exploring raw sources.
1717
- [GitHub Actions performance plan](./workflows/ci-performance-plan.md) - PR/full matrix, sharding, test-runtime improvements, and acceptance criteria based on measured CI bottlenecks.
1818
- [CI parallel test metrics](./workflows/ci-parallel-test-metrics.md) - Test concurrency, resolved worker settings, retries, and shard inventories in CI artifacts.
1919
- [Docs and API Updates](./workflows/docs-and-api-updates.md) - How to handle changes that affect user-facing docs or durable project understanding.
20-
- [Local CI](./workflows/local-ci.md) - Local validation should run tests from clean sources and avoid stale artifacts (`dist/` duplicate-proto; fixture `.egg` scan-manifest caches) before tegg tests.
20+
- [Local CI](./workflows/local-ci.md) - Local validation and scripts Windows preload coverage; run main tests from clean sources and avoid stale artifacts (`dist/` duplicate-proto; fixture `.egg` scan-manifest caches) before tegg tests.
2121
- [PR preview packages](./workflows/pr-preview-packages.md) - Publish workspace previews through a pull request label and install them in consumer applications, including from stacked PRs.
2222
- [Egg-bin Windows shell probe hotspot](./workflows/egg-bin-windows-shell-probe.md) - How PR #6014 diagnosed hosted-Windows egg-bin startup slowness and why the final fix only presets SHELL.
2323

‎wiki/log.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,3 +532,10 @@ Full **isolate:false suite validated GREEN** under CI-faithful parallelism (`--m
532532

533533
- Removed the exact packageManager pin, restored the utoo catalog range to ^1, and switched CI/bootstrap instructions to latest at the user’s request. Native workspace/catalog configuration remains authoritative.
534534
- Removed the E2E-only utoo@1.1.1 temporary installation; packing now reuses the latest CLI from setup-utoo and the tracked native configuration.
535+
536+
## 2026-10-06 — Scripts Windows sourcemap regression coverage
537+
538+
- Added Windows Node.js 24 coverage for ESM file URL preloads, special-character paths, CJS preloads, and foreground child exit handling in `.github/workflows/ci.yml` and `tools/scripts/test/start-unit.test.ts`.
539+
- Refreshed [Local CI](./workflows/local-ci.md) to describe the targeted Windows job and scripts-only build prerequisite.
540+
541+
- Windows source-level regression tests skip the Linux CLI build step: utoo interprets its tsdown path filter as a workspace selection on Windows, while these tests do not require `dist`.

‎wiki/workflows/local-ci.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ source_files:
1414
- tools/create-egg/package.json
1515
- tools/egg-bin/package.json
1616
- tools/egg-bin/tsconfig.json
17+
- tools/scripts/test/start-unit.test.ts
1718
- tools/scripts/src/commands/start.ts
1819
- packages/egg/src/lib/core/httpclient.ts
1920
- tegg/core/loader/src/impl/ModuleLoader.ts
@@ -37,7 +38,13 @@ the complete Node.js 22/24/26 × Linux/macOS/Windows matrix without sharding. It
3738
coverage job, without building packages before tests.
3839

3940
The egg-bin matrix runs Node.js 24 and 26 on Linux and Windows. The egg-scripts
40-
matrix runs Node.js 22, 24, and 26 on Linux. The tegg Vitest adapter runs both
41+
matrix runs Node.js 22, 24, and 26 on Linux, plus targeted preload and foreground
42+
exit regression tests on Windows Node.js 24. The Windows tests load
43+
source-map-support through real Node subprocesses from paths containing spaces
44+
and `#`, covering ESM file URLs and unchanged CJS `--require` paths. The
45+
Linux egg-scripts jobs build only that CLI before their tests because its bin discovers
46+
commands from `dist`; the targeted Windows job imports sources and skips that
47+
build. This differs from the main suite. The tegg Vitest adapter runs both
4148
isolated and shared workers on Node.js 24 and 26 on Linux. Coverage reports
4249
come from the Linux Node.js 24 jobs. The main-suite coverage job checks the
4350
complete, disjoint shard inventory before merging Vitest blob coverage reports.

0 commit comments

Comments
 (0)