|
| 1 | +import { describe, it, expect, beforeEach, afterEach } from "vitest"; |
| 2 | +import { isMainModule } from "../src/is-main-module.js"; |
| 3 | +import { writeFileSync, symlinkSync, realpathSync, mkdirSync, rmSync } from "node:fs"; |
| 4 | +import { tmpdir } from "node:os"; |
| 5 | +import { join } from "node:path"; |
| 6 | + |
| 7 | +const TMP = join(tmpdir(), "perplexity-is-main-module-test"); |
| 8 | + |
| 9 | +function cleanTmp() { |
| 10 | + try { rmSync(TMP, { recursive: true }); } catch { /* ignore */ } |
| 11 | +} |
| 12 | + |
| 13 | +describe("isMainModule", () => { |
| 14 | + beforeEach(() => { |
| 15 | + cleanTmp(); |
| 16 | + mkdirSync(TMP, { recursive: true }); |
| 17 | + }); |
| 18 | + afterEach(() => { |
| 19 | + cleanTmp(); |
| 20 | + delete process.argv[1]; |
| 21 | + }); |
| 22 | + |
| 23 | + it("returns true when argv[1] matches import.meta.url exactly", () => { |
| 24 | + const realFile = join(TMP, "real.mjs"); |
| 25 | + writeFileSync(realFile, ""); |
| 26 | + process.argv[1] = realFile; |
| 27 | + const metaUrl = "file://" + realFile.replace(/\\/g, "/"); |
| 28 | + expect(isMainModule(metaUrl)).toBe(true); |
| 29 | + }); |
| 30 | + |
| 31 | + it("returns false when argv[1] points at a different file", () => { |
| 32 | + const realFile = join(TMP, "real.mjs"); |
| 33 | + const otherFile = join(TMP, "other.mjs"); |
| 34 | + writeFileSync(realFile, ""); |
| 35 | + writeFileSync(otherFile, ""); |
| 36 | + process.argv[1] = otherFile; |
| 37 | + const metaUrl = "file://" + realFile.replace(/\\/g, "/"); |
| 38 | + expect(isMainModule(metaUrl)).toBe(false); |
| 39 | + }); |
| 40 | + |
| 41 | + it("returns true when argv[1] is a symlink to the real file (issue #6)", () => { |
| 42 | + const realFile = join(TMP, "real.mjs"); |
| 43 | + const linkFile = join(TMP, "link.mjs"); |
| 44 | + writeFileSync(realFile, ""); |
| 45 | + symlinkSync(realFile, linkFile); |
| 46 | + process.argv[1] = linkFile; |
| 47 | + const metaUrl = "file://" + realFile.replace(/\\/g, "/"); |
| 48 | + expect(isMainModule(metaUrl)).toBe(true); |
| 49 | + }); |
| 50 | + |
| 51 | + it("returns false when argv[1] is missing", () => { |
| 52 | + delete process.argv[1]; |
| 53 | + expect(isMainModule("file:///any/path.mjs")).toBe(false); |
| 54 | + }); |
| 55 | +}); |
0 commit comments