/** * 入口判断的测试 —— 这个缺陷只在**部署形态**下出现,所以必须专门钉住。 * * 实测经过:生产布局是 `current` 软链,入口用 * `import.meta.url === 'file://' + process.argv[1]` 判断是否直接执行 —— * `import.meta.url` 是解析过软链的真实路径,argv 是软链路径,两者不等, * 于是 `main()` 从不执行:**没有输出、没有报错、退出码 0**。 * * 从仓库路径跑(无软链)完全正常,所以本地怎么试都发现不了。 */ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { isMainModule } from '../lib/is-main.mjs'; test('同一个文件的真实路径 → 是入口', () => { const url = pathToFileURL('/etc/hostname').href; assert.equal(isMainModule(url, '/etc/hostname'), true); }); test('★ 通过软链指向自己 → 仍是入口(生产布局就是软链)', async () => { const dir = await mkdtemp(join(tmpdir(), 'zc-is-main-')); try { const real = join(dir, 'real.mjs'); const link = join(dir, 'current.mjs'); await writeFile(real, '// x\n', 'utf8'); await symlink(real, link); const url = pathToFileURL(real).href; assert.equal( isMainModule(url, link), true, '软链路径必须被认成同一个文件 —— 否则快照部署下入口静默不执行' ); } finally { await rm(dir, { recursive: true, force: true }); } }); test('★ 目录软链(current → <时间戳>)下的完整路径同样成立', async () => { // 生产的软链在**目录**这一层:/opt/...//current/mcp/server.mjs const dir = await mkdtemp(join(tmpdir(), 'zc-is-main-d-')); try { await mkdir(join(dir, '20260101-000000', 'mcp'), { recursive: true }); const real = join(dir, '20260101-000000', 'mcp', 'server.mjs'); await writeFile(real, '// x\n', 'utf8'); await symlink('20260101-000000', join(dir, 'current')); assert.equal( isMainModule(pathToFileURL(real).href, join(dir, 'current', 'mcp', 'server.mjs')), true ); } finally { await rm(dir, { recursive: true, force: true }); } }); test('★ 反向对照:别的文件不是入口', () => { assert.equal(isMainModule(pathToFileURL('/etc/hostname').href, '/etc/hosts'), false); }); test('缺失的 argv 或文件不存在 → 保守判否(不误跑一遍)', () => { assert.equal(isMainModule(pathToFileURL('/etc/hostname').href, ''), false); assert.equal(isMainModule(pathToFileURL('/etc/hostname').href, undefined), false); assert.equal(isMainModule(pathToFileURL('/etc/hostname').href, '/no/such/file/xyz'), false); assert.equal(isMainModule('', '/etc/hostname'), false); });