From 4768509774e6bf2c363ce47ef342fc9074a8bd4a Mon Sep 17 00:00:00 2001 From: Rodolphe Stoclin Date: Fri, 9 Oct 2026 12:21:12 +0200 Subject: [PATCH 1/4] fix(release): fail the publish job instead of swallowing npm errors scripts/publish.ts caught every `npm publish` failure as "may already exist" and still exited 0, so an auth or registry failure would release nothing and stay green. It also ran `changeset tag` unconditionally: on every push to main without a release, CI tried to republish all 22 packages, `changeset tag` printed "New tag:" for each, changesets/action read that as a release, and `gh release create v11.0.0` failed with HTTP 422 (publish runs of 2026-09-02 for #2906 and #2907). Now each package is checked with `npm view name@version` first: an exact match is skipped, E404 is published, any other lookup error or publish failure stops the run with exit 1. Tags are only created when something was published. The entry point is guarded by `import.meta.main` so the script can be imported by its test without publishing. --- scripts/__tests__/publish.test.ts | 47 +++++++++++++ scripts/publish.ts | 105 ++++++++++++++++++++++-------- vitest.config.ts | 2 +- 3 files changed, 126 insertions(+), 28 deletions(-) create mode 100644 scripts/__tests__/publish.test.ts diff --git a/scripts/__tests__/publish.test.ts b/scripts/__tests__/publish.test.ts new file mode 100644 index 000000000..68710170b --- /dev/null +++ b/scripts/__tests__/publish.test.ts @@ -0,0 +1,47 @@ +/*! node-minify - MIT Licensed */ + +import { describe, expect, test } from "vitest"; +import { isPublished } from "../publish.ts"; + +const e404 = JSON.stringify({ error: { code: "E404", summary: "Not found" } }); + +describe("isPublished", () => { + test("is true when npm view returns the exact version", () => { + expect( + isPublished("11.0.0", { status: 0, stdout: '"11.0.0"', stderr: "" }) + ).toBe(true); + expect( + isPublished("11.0.0", { + status: 0, + stdout: '[\n "11.0.0"\n]', + stderr: "", + }) + ).toBe(true); + }); + + test("is false when npm view answers E404", () => { + expect( + isPublished("11.0.1", { status: 1, stdout: e404, stderr: "" }) + ).toBe(false); + }); + + test("is false when npm view succeeds without the version", () => { + expect( + isPublished("11.0.1", { status: 0, stdout: "", stderr: "" }) + ).toBe(false); + }); + + test("throws on any other npm view failure", () => { + const e403 = JSON.stringify({ error: { code: "E403" } }); + expect(() => + isPublished("11.0.1", { status: 1, stdout: e403, stderr: "" }) + ).toThrow(/npm view failed/); + expect(() => + isPublished("11.0.1", { + status: 1, + stdout: "", + stderr: "network down", + }) + ).toThrow(/network down/); + }); +}); diff --git a/scripts/publish.ts b/scripts/publish.ts index 97bb75023..69ca2bc23 100644 --- a/scripts/publish.ts +++ b/scripts/publish.ts @@ -1,7 +1,7 @@ #!/usr/bin/env bun /*! node-minify - MIT Licensed */ -import { execSync } from "node:child_process"; +import { execSync, spawnSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -16,6 +16,8 @@ interface PackageJson { optionalDependencies?: Record; } +export type CommandResult = { status: number; stdout: string; stderr: string }; + const __dirname = dirname(fileURLToPath(import.meta.url)); const PACKAGES_DIR = join(__dirname, "..", "packages"); @@ -97,9 +99,55 @@ function resolveDependencies( } /** - * Publishes non-private workspace packages and creates changeset tags. + * Read an `npm view @ version --json` result. Only an exact + * match counts as published; E404 means not yet; any other failure throws, so + * a broken registry or auth never reads as "already published". + * + * @param version - The version being released + * @param view - The exit status and output of `npm view` + * @returns `true` if that exact version is on the registry + * @throws {Error} When `npm view` fails for any reason other than E404 + */ +export function isPublished(version: string, view: CommandResult): boolean { + if (view.status !== 0) { + if (errorCode(view.stdout) === "E404") return false; + const output = `${view.stdout}${view.stderr}`.trim() || "no output"; + throw new Error(`npm view failed (exit ${view.status}): ${output}`); + } + if (view.stdout.trim() === "") return false; + const parsed: unknown = JSON.parse(view.stdout); + return (Array.isArray(parsed) ? parsed : [parsed]).includes(version); +} + +function errorCode(stdout: string): string | undefined { + try { + return JSON.parse(stdout)?.error?.code; + } catch { + return undefined; + } +} + +function npmView(name: string, version: string): CommandResult { + const result = spawnSync( + "npm", + ["view", `${name}@${version}`, "version", "--json"], + { encoding: "utf-8" } + ); + if (result.error) throw result.error; + return { + status: result.status ?? 1, + stdout: result.stdout, + stderr: result.stderr, + }; +} + +/** + * Publishes every non-private workspace package not already on the registry, + * then creates changeset tags if anything was published. * - * For each package under the packages directory, resolves `workspace:` dependency references to actual package versions, writes the updated package.json, attempts `npm publish --access public --provenance`, restores the original package.json, and logs progress. After processing all packages, runs `changeset tag` to create git tags; publish or tag failures are logged but do not stop processing. + * A version is skipped only when the registry returns that exact version. Any + * other lookup or publish failure stops the run with a non-zero exit, so the + * release job cannot go green without shipping. * * @returns Nothing. */ @@ -109,6 +157,7 @@ function main() { console.log(`Found ${packageDirs.length} packages to publish\n`); + let published = 0; for (const dir of packageDirs) { const pkgPath = join(PACKAGES_DIR, dir, "package.json"); const originalContent = readFileSync(pkgPath, "utf-8"); @@ -119,6 +168,11 @@ function main() { continue; } + if (isPublished(pkg.version, npmView(pkg.name, pkg.version))) { + console.log(`Already on npm: ${pkg.name}@${pkg.version}`); + continue; + } + pkg.dependencies = resolveDependencies(pkg.dependencies, versionMap); pkg.devDependencies = resolveDependencies( pkg.devDependencies, @@ -142,40 +196,37 @@ function main() { cwd: join(PACKAGES_DIR, dir), stdio: "inherit", }); + published++; console.log(`Published ${pkg.name}@${pkg.version}\n`); - } catch (err) { - if (err instanceof Error) { - console.log( - `Failed to publish ${pkg.name}@${pkg.version} (may already exist)\n` - ); - } } finally { writeFileSync(pkgPath, originalContent); } } - console.log("\nCreating git tags..."); - try { - execSync("changeset tag", { - cwd: join(__dirname, ".."), - stdio: "inherit", - }); - } catch (err) { - if (err instanceof Error) { - console.log("Failed to create tags (may already exist)"); - } + // No publish, no tags: changesets/action reads "New tag:" lines as a release. + if (published === 0) { + console.log("\nNothing to publish, no tags created."); + return; } + console.log("\nCreating git tags..."); + execSync("changeset tag", { + cwd: join(__dirname, ".."), + stdio: "inherit", + }); + console.log("\nDone!"); } -try { - main(); -} catch (error) { - if (error instanceof Error) { - console.error("Publish failed:", error.message); - } else { - console.error("Publish failed:", error); +if (import.meta.main) { + try { + main(); + } catch (error) { + if (error instanceof Error) { + console.error("Publish failed:", error.message); + } else { + console.error("Publish failed:", error); + } + process.exit(1); } - process.exit(1); } diff --git a/vitest.config.ts b/vitest.config.ts index 54e9eaefb..25b27fd23 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [tsconfigPaths()], test: { - projects: ["packages/*"], + projects: ["packages/*", "scripts"], reporters: ["default"], coverage: { reporter: ["text", "json", "html"], From d7f22e4f807aef97f1a36c3ed149206e3bea557b Mon Sep 17 00:00:00 2001 From: Rodolphe Stoclin Date: Fri, 9 Oct 2026 13:46:32 +0200 Subject: [PATCH 2/4] fix(release): time out a registry lookup that never answers --- scripts/publish.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/publish.ts b/scripts/publish.ts index 69ca2bc23..e67be4936 100644 --- a/scripts/publish.ts +++ b/scripts/publish.ts @@ -131,7 +131,8 @@ function npmView(name: string, version: string): CommandResult { const result = spawnSync( "npm", ["view", `${name}@${version}`, "version", "--json"], - { encoding: "utf-8" } + // A registry that never answers would otherwise hold the job for 6h. + { encoding: "utf-8", timeout: 120_000 } ); if (result.error) throw result.error; return { From f9fefb0e6a92bf1374ac987f6d7bd077479f8eec Mon Sep 17 00:00:00 2001 From: Rodolphe Stoclin Date: Fri, 9 Oct 2026 13:53:39 +0200 Subject: [PATCH 3/4] test(release): cover the publish loop with an injected command runner publishAll takes the packages directory and the command runner, so the tests can check without a registry: no tags when everything is already on npm, only missing packages published with workspace deps resolved, and a failed publish stopping the run with its package.json restored. --- scripts/__tests__/publish.test.ts | 113 ++++++++++++++++++++++++- scripts/publish.ts | 135 +++++++++++++++++++----------- 2 files changed, 198 insertions(+), 50 deletions(-) diff --git a/scripts/__tests__/publish.test.ts b/scripts/__tests__/publish.test.ts index 68710170b..87b43c431 100644 --- a/scripts/__tests__/publish.test.ts +++ b/scripts/__tests__/publish.test.ts @@ -1,7 +1,10 @@ /*! node-minify - MIT Licensed */ -import { describe, expect, test } from "vitest"; -import { isPublished } from "../publish.ts"; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; +import { beforeEach, describe, expect, test } from "vitest"; +import { type CommandResult, isPublished, publishAll } from "../publish.ts"; const e404 = JSON.stringify({ error: { code: "E404", summary: "Not found" } }); @@ -45,3 +48,109 @@ describe("isPublished", () => { ).toThrow(/network down/); }); }); + +type Call = { + command: string; + args: string[]; + cwd?: string; + manifest?: string; +}; + +describe("publishAll", () => { + let packagesDir: string; + const manifests: Record = { + core: { + name: "@node-minify/core", + version: "11.0.1", + dependencies: { "@node-minify/utils": "workspace:*" }, + }, + utils: { name: "@node-minify/utils", version: "11.0.1" }, + }; + + beforeEach(() => { + packagesDir = mkdtempSync(join(tmpdir(), "publish-test-")); + for (const [dir, manifest] of Object.entries(manifests)) { + mkdirSync(join(packagesDir, dir)); + writeFileSync( + join(packagesDir, dir, "package.json"), + `${JSON.stringify(manifest, null, 2)}\n` + ); + } + }); + + const manifestOf = (dir: string) => + readFileSync(join(packagesDir, dir, "package.json"), "utf-8"); + + /** Fake runner: `onRegistry` lists published dirs, `failPublish` the dir whose publish fails. */ + function fakeRun(onRegistry: string[], failPublish?: string) { + const calls: Call[] = []; + const run = ( + command: string, + args: string[], + options: { cwd?: string } = {} + ): CommandResult => { + const call: Call = { command, args, cwd: options.cwd }; + calls.push(call); + if (args[0] === "view") { + const dir = args[1].split("/")[1].split("@")[0]; + return onRegistry.includes(dir) + ? { status: 0, stdout: '"11.0.1"', stderr: "" } + : { status: 1, stdout: e404, stderr: "" }; + } + if (args[0] === "publish" && options.cwd) { + call.manifest = manifestOf(basename(options.cwd)); + if (basename(options.cwd) === failPublish) { + return { status: 1, stdout: "", stderr: "" }; + } + } + return { status: 0, stdout: "", stderr: "" }; + }; + return { run, calls }; + } + + const options = (run: ReturnType["run"]) => ({ + packagesDir, + repoRoot: packagesDir, + run, + log: () => {}, + }); + + test("creates no tags when every version is already on npm", () => { + const { run, calls } = fakeRun(["core", "utils"]); + expect(publishAll(options(run))).toBe(0); + expect(calls.map((c) => c.args[0])).toEqual(["view", "view"]); + }); + + test("publishes only what is missing, with workspace deps resolved, then tags", () => { + const before = manifestOf("core"); + const { run, calls } = fakeRun(["utils"]); + + expect(publishAll(options(run))).toBe(1); + + const publishes = calls.filter((c) => c.args[0] === "publish"); + expect(publishes.map((c) => basename(c.cwd ?? ""))).toEqual(["core"]); + expect(JSON.parse(publishes[0].manifest ?? "{}").dependencies).toEqual({ + "@node-minify/utils": "11.0.1", + }); + expect(manifestOf("core")).toBe(before); + expect(calls.at(-1)).toMatchObject({ + command: "changeset", + args: ["tag"], + }); + }); + + test("stops at a failed publish, restores its package.json and creates no tags", () => { + const before = manifestOf("core"); + const { run, calls } = fakeRun([], "core"); + + expect(() => publishAll(options(run))).toThrow( + /npm publish @node-minify\/core@11.0.1 failed/ + ); + + expect(manifestOf("core")).toBe(before); + expect(calls.some((c) => basename(c.cwd ?? "") === "utils")).toBe( + false + ); + expect(calls.some((c) => c.command === "changeset")).toBe(false); + }); +}); diff --git a/scripts/publish.ts b/scripts/publish.ts index e67be4936..2f836c1d8 100644 --- a/scripts/publish.ts +++ b/scripts/publish.ts @@ -1,7 +1,7 @@ #!/usr/bin/env bun /*! node-minify - MIT Licensed */ -import { execSync, spawnSync } from "node:child_process"; +import { spawnSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -18,19 +18,26 @@ interface PackageJson { export type CommandResult = { status: number; stdout: string; stderr: string }; -const __dirname = dirname(fileURLToPath(import.meta.url)); -const PACKAGES_DIR = join(__dirname, "..", "packages"); +/** Runs a command; `inherit` streams its output to this process instead of capturing it. */ +export type Run = ( + command: string, + args: string[], + options?: { cwd?: string; inherit?: boolean } +) => CommandResult; + +const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); /** * List package directory names inside the packages directory that contain a package.json file. * - * @returns A sorted (alphabetical) array of directory names under PACKAGES_DIR that contain a package.json + * @param packagesDir - The directory holding the workspace packages + * @returns A sorted (alphabetical) array of directory names under packagesDir that contain a package.json */ -function getPackageDirs(): string[] { - return readdirSync(PACKAGES_DIR, { withFileTypes: true }) +function getPackageDirs(packagesDir: string): string[] { + return readdirSync(packagesDir, { withFileTypes: true }) .filter((entry) => entry.isDirectory()) .filter((entry) => - existsSync(join(PACKAGES_DIR, entry.name, "package.json")) + existsSync(join(packagesDir, entry.name, "package.json")) ) .map((entry) => entry.name) .sort(); @@ -39,24 +46,26 @@ function getPackageDirs(): string[] { /** * Read and parse the package.json file for a package located under the packages root. * - * @param packageDir - The directory name of the package inside PACKAGES_DIR + * @param packagesDir - The directory holding the workspace packages + * @param packageDir - The directory name of the package inside packagesDir * @returns The parsed package.json as a `PackageJson` */ -function readPackageJson(packageDir: string): PackageJson { - const pkgPath = join(PACKAGES_DIR, packageDir, "package.json"); +function readPackageJson(packagesDir: string, packageDir: string): PackageJson { + const pkgPath = join(packagesDir, packageDir, "package.json"); return JSON.parse(readFileSync(pkgPath, "utf-8")); } /** * Builds a map from each package's name to its version by reading package.json for all packages. * + * @param packagesDir - The directory holding the workspace packages * @returns A Map where each key is a package name and each value is that package's version string. */ -function buildVersionMap(): Map { +function buildVersionMap(packagesDir: string): Map { const versionMap = new Map(); - for (const dir of getPackageDirs()) { - const pkg = readPackageJson(dir); + for (const dir of getPackageDirs(packagesDir)) { + const pkg = readPackageJson(packagesDir, dir); versionMap.set(pkg.name, pkg.version); } @@ -127,19 +136,27 @@ function errorCode(stdout: string): string | undefined { } } -function npmView(name: string, version: string): CommandResult { - const result = spawnSync( - "npm", - ["view", `${name}@${version}`, "version", "--json"], - // A registry that never answers would otherwise hold the job for 6h. - { encoding: "utf-8", timeout: 120_000 } - ); +const spawnRun: Run = (command, args, options = {}) => { + const result = spawnSync(command, args, { + cwd: options.cwd, + encoding: "utf-8", + stdio: options.inherit ? "inherit" : "pipe", + // Only captured lookups time out: a registry that never answers would + // otherwise hold the job for 6h. Publishes and tagging stream and run long. + timeout: options.inherit ? undefined : 120_000, + }); if (result.error) throw result.error; return { status: result.status ?? 1, - stdout: result.stdout, - stderr: result.stderr, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", }; +}; + +function succeed(label: string, result: CommandResult): void { + if (result.status !== 0) { + throw new Error(`${label} failed (exit ${result.status})`); + } } /** @@ -147,30 +164,44 @@ function npmView(name: string, version: string): CommandResult { * then creates changeset tags if anything was published. * * A version is skipped only when the registry returns that exact version. Any - * other lookup or publish failure stops the run with a non-zero exit, so the - * release job cannot go green without shipping. + * other lookup or publish failure throws, so the release job cannot go green + * without shipping. Each rewritten package.json is restored after its publish. * - * @returns Nothing. + * @param options - `packagesDir` holds the packages, `repoRoot` is where `changeset tag` runs, `run` executes commands + * @returns The number of packages published + * @throws {Error} When a lookup, publish, or `changeset tag` fails */ -function main() { - const packageDirs = getPackageDirs(); - const versionMap = buildVersionMap(); +export function publishAll(options: { + packagesDir: string; + repoRoot: string; + run: Run; + log?: (line: string) => void; +}): number { + const { packagesDir, repoRoot, run, log = console.log } = options; + const packageDirs = getPackageDirs(packagesDir); + const versionMap = buildVersionMap(packagesDir); - console.log(`Found ${packageDirs.length} packages to publish\n`); + log(`Found ${packageDirs.length} packages to publish\n`); let published = 0; for (const dir of packageDirs) { - const pkgPath = join(PACKAGES_DIR, dir, "package.json"); + const pkgPath = join(packagesDir, dir, "package.json"); const originalContent = readFileSync(pkgPath, "utf-8"); const pkg: PackageJson = JSON.parse(originalContent); if (pkg.private) { - console.log(`Skipping private package: ${pkg.name}`); + log(`Skipping private package: ${pkg.name}`); continue; } - if (isPublished(pkg.version, npmView(pkg.name, pkg.version))) { - console.log(`Already on npm: ${pkg.name}@${pkg.version}`); + const view = run("npm", [ + "view", + `${pkg.name}@${pkg.version}`, + "version", + "--json", + ]); + if (isPublished(pkg.version, view)) { + log(`Already on npm: ${pkg.name}@${pkg.version}`); continue; } @@ -190,15 +221,18 @@ function main() { writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`); - console.log(`Publishing ${pkg.name}@${pkg.version}...`); + log(`Publishing ${pkg.name}@${pkg.version}...`); try { - execSync("npm publish --access public --provenance", { - cwd: join(PACKAGES_DIR, dir), - stdio: "inherit", - }); + succeed( + `npm publish ${pkg.name}@${pkg.version}`, + run("npm", ["publish", "--access", "public", "--provenance"], { + cwd: join(packagesDir, dir), + inherit: true, + }) + ); published++; - console.log(`Published ${pkg.name}@${pkg.version}\n`); + log(`Published ${pkg.name}@${pkg.version}\n`); } finally { writeFileSync(pkgPath, originalContent); } @@ -206,22 +240,27 @@ function main() { // No publish, no tags: changesets/action reads "New tag:" lines as a release. if (published === 0) { - console.log("\nNothing to publish, no tags created."); - return; + log("\nNothing to publish, no tags created."); + return 0; } - console.log("\nCreating git tags..."); - execSync("changeset tag", { - cwd: join(__dirname, ".."), - stdio: "inherit", - }); + log("\nCreating git tags..."); + succeed( + "changeset tag", + run("changeset", ["tag"], { cwd: repoRoot, inherit: true }) + ); - console.log("\nDone!"); + log("\nDone!"); + return published; } if (import.meta.main) { try { - main(); + publishAll({ + packagesDir: join(REPO_ROOT, "packages"), + repoRoot: REPO_ROOT, + run: spawnRun, + }); } catch (error) { if (error instanceof Error) { console.error("Publish failed:", error.message); From a12c4fdcdca2112961221d69af7d18d4d662ea13 Mon Sep 17 00:00:00 2001 From: Rodolphe Stoclin Date: Fri, 9 Oct 2026 14:00:19 +0200 Subject: [PATCH 4/4] test(release): remove each test's temp package tree --- scripts/__tests__/publish.test.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/scripts/__tests__/publish.test.ts b/scripts/__tests__/publish.test.ts index 87b43c431..b5b838869 100644 --- a/scripts/__tests__/publish.test.ts +++ b/scripts/__tests__/publish.test.ts @@ -1,9 +1,15 @@ /*! node-minify - MIT Licensed */ -import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { basename, join } from "node:path"; -import { beforeEach, describe, expect, test } from "vitest"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; import { type CommandResult, isPublished, publishAll } from "../publish.ts"; const e404 = JSON.stringify({ error: { code: "E404", summary: "Not found" } }); @@ -78,6 +84,10 @@ describe("publishAll", () => { } }); + afterEach(() => { + rmSync(packagesDir, { recursive: true, force: true }); + }); + const manifestOf = (dir: string) => readFileSync(join(packagesDir, dir, "package.json"), "utf-8");