From 2d83b3ea4a66f96e652852c9bb95d4d752b3fa43 Mon Sep 17 00:00:00 2001 From: Roger Chappel Date: Sat, 9 May 2026 21:49:13 +1000 Subject: [PATCH] Make CLI import safe --- src/cli.ts | 11 +++++++---- test/cli.test.ts | 9 +++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 701dc8c..1f737e9 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { pathToFileURL } from "node:url"; import { generatePrPack } from "./generate.js"; interface CliOptions { @@ -103,7 +104,9 @@ export async function run(argv = process.argv.slice(2)): Promise { } } -run().catch((error: unknown) => { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 1; -}); +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + run().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/test/cli.test.ts b/test/cli.test.ts index 414b551..848440a 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; +import { access, rm } from "node:fs/promises"; import { promisify } from "node:util"; import { describe, it } from "node:test"; @@ -17,4 +18,12 @@ void describe("cli", () => { assert.equal(parsed.pack.title, "Add deterministic PR pack generation"); assert.match(parsed.pack.prBody, /Reviewer Checklist/); }); + + void it("can be imported without running the CLI", async () => { + await rm("PR_PACK.md", { force: true }); + const { stdout } = await execFileAsync(process.execPath, ["--input-type=module", "--eval", "import('./dist/src/cli.js').then((mod) => console.log(typeof mod.run))"]); + + assert.equal(stdout.trim(), "function"); + await assert.rejects(() => access("PR_PACK.md")); + }); });