refactor(release): centralize publishable package roster

This commit is contained in:
Miguel Ángel
2026-08-23 20:04:16 +00:00
parent 32d58a73e3
commit 2954e72a7d
6 changed files with 577 additions and 81 deletions
+118
View File
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import { runPublishPackages, type PublishCommand } from "./publish-packages.ts";
import { type PublishablePackage } from "./release-packages.ts";
const normal: PublishablePackage = {
workspacePath: "packages/core",
workspaceName: "@hyperframes/core",
npmName: "@hyperframes/core",
publishMode: "workspace",
};
const cli: PublishablePackage = {
workspacePath: "packages/cli",
workspaceName: "@hyperframes/cli",
npmName: "hyperframes",
publishMode: "manifest-name-override",
};
function fixture(): string {
const root = mkdtempSync(join(tmpdir(), "hf-publish-packages-"));
writeFileSync(join(root, "package.json"), JSON.stringify({ workspaces: ["packages/*"] }));
for (const entry of [normal, cli]) {
mkdirSync(join(root, entry.workspacePath), { recursive: true });
writeFileSync(
join(root, entry.workspacePath, "package.json"),
`${JSON.stringify({ name: entry.workspaceName, version: "1.2.3" }, null, 2)}\n`,
);
}
return root;
}
// fallow-ignore-next-line unit-size
describe("shared package publisher", () => {
it("skips existing versions and publishes missing workspaces in roster order", async () => {
const root = fixture();
const calls: string[] = [];
const command: PublishCommand = async (executable, args, cwd) => {
calls.push(`${executable} ${args.join(" ")} @ ${cwd}`);
};
try {
const result = await runPublishPackages(
{ root, version: "1.2.3", distTag: "latest", roster: [normal, cli] },
{
packageExists: async (name) => name === normal.npmName,
command,
log: () => undefined,
},
);
assert.deepEqual(result, {
published: ["hyperframes"],
skipped: ["@hyperframes/core"],
failed: [],
});
assert.deepEqual(calls, [
`npm publish --access public --tag latest @ ${join(root, "packages/cli")}`,
]);
assert.equal(
JSON.parse(readFileSync(join(root, "packages/cli/package.json"), "utf8")).name,
"@hyperframes/cli",
);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("aggregates failures, continues, and restores CLI manifest bytes", async () => {
const root = fixture();
const cliManifest = join(root, "packages/cli/package.json");
const original = readFileSync(cliManifest, "utf8");
const calls: string[] = [];
try {
await assert.rejects(
runPublishPackages(
{ root, version: "1.2.3", distTag: "latest", roster: [normal, cli] },
{
packageExists: async () => false,
command: async (executable, args) => {
calls.push(`${executable} ${args.join(" ")}`);
throw new Error("publish failed");
},
log: () => undefined,
},
),
/@hyperframes\/core, hyperframes/,
);
assert.equal(calls.length, 2);
assert.equal(readFileSync(cliManifest, "utf8"), original);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("fails reconciliation before any npm boundary when a public workspace is omitted", async () => {
const root = fixture();
let calls = 0;
try {
await assert.rejects(
runPublishPackages(
{ root, version: "1.2.3", distTag: "latest", roster: [normal] },
{
packageExists: async () => false,
command: async () => {
calls += 1;
},
log: () => undefined,
},
),
/public workspace.*@hyperframes\/cli.*missing/i,
);
assert.equal(calls, 0);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env tsx
import { execFile } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { promisify } from "node:util";
import { pathToFileURL } from "node:url";
import {
PUBLISHABLE_PACKAGES,
validatePublishablePackages,
type PublishablePackage,
} from "./release-packages.ts";
const execFileAsync = promisify(execFile);
export type PublishCommand = (
executable: string,
args: readonly string[],
cwd: string,
) => Promise<void>;
type PublishDependencies = {
packageExists: (npmName: string, version: string) => Promise<boolean>;
command: PublishCommand;
log: (message: string) => void;
};
type PublishInput = {
root: string;
version: string;
distTag: string;
roster?: readonly PublishablePackage[];
};
type PublishResult = { published: string[]; skipped: string[]; failed: string[] };
// The two allowed publish modes converge here so CLI restoration cannot be bypassed.
// fallow-ignore-next-line complexity
async function publishEntry(
root: string,
entry: PublishablePackage,
distTag: string,
command: PublishCommand,
): Promise<void> {
if (entry.publishMode === "workspace") {
await command(
"pnpm",
[
"--filter",
entry.workspaceName,
"publish",
"--access",
"public",
"--no-git-checks",
"--tag",
distTag,
],
root,
);
return;
}
const workspace = join(root, entry.workspacePath);
const manifestPath = join(workspace, "package.json");
const original = readFileSync(manifestPath, "utf8");
const manifest: unknown = JSON.parse(original);
if (!manifest || typeof manifest !== "object" || Array.isArray(manifest))
throw new Error(`Invalid package manifest at ${manifestPath}.`);
try {
writeFileSync(
manifestPath,
`${JSON.stringify({ ...manifest, name: entry.npmName }, null, 2)}\n`,
);
await command("npm", ["publish", "--access", "public", "--tag", distTag], workspace);
} finally {
writeFileSync(manifestPath, original);
}
}
// Continue-and-aggregate is deliberate: every missing package gets one attempt per rerun.
// fallow-ignore-next-line complexity
export async function runPublishPackages(
input: PublishInput,
dependencies: PublishDependencies,
): Promise<PublishResult> {
const roster = validatePublishablePackages(input.root, input.roster ?? PUBLISHABLE_PACKAGES);
const result: PublishResult = { published: [], skipped: [], failed: [] };
for (const entry of roster) {
if (await dependencies.packageExists(entry.npmName, input.version)) {
dependencies.log(`⏭️ ${entry.npmName}@${input.version} already published — skipping`);
result.skipped.push(entry.npmName);
continue;
}
dependencies.log(`📦 Publishing ${entry.npmName}@${input.version}...`);
try {
await publishEntry(input.root, entry, input.distTag, dependencies.command);
dependencies.log(`✅ ${entry.npmName}@${input.version} published`);
result.published.push(entry.npmName);
} catch {
dependencies.log(`❌ ${entry.npmName}@${input.version} failed to publish`);
result.failed.push(entry.npmName);
}
}
if (result.failed.length > 0)
throw new Error(`Packages failed to publish: ${result.failed.join(", ")}`);
return result;
}
const defaultDependencies: PublishDependencies = {
packageExists: async (npmName, version) => {
try {
await execFileAsync("npm", ["view", `${npmName}@${version}`, "version"]);
return true;
} catch {
return false;
}
},
command: async (executable, args, cwd) => {
await execFileAsync(executable, [...args], { cwd });
},
log: console.log,
};
// fallow-ignore-next-line complexity
async function main(): Promise<void> {
const version = process.env.VERSION ?? "";
const distTag = process.env.DIST_TAG ?? "";
if (!version || !distTag) throw new Error("VERSION and DIST_TAG are required.");
await runPublishPackages(
{ root: join(import.meta.dirname, ".."), version, distTag },
defaultDependencies,
);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((error: unknown) => {
console.error(`::error::${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
}
+140
View File
@@ -0,0 +1,140 @@
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import {
PUBLISHABLE_PACKAGES,
discoverWorkspacePackages,
validatePublishablePackages,
type PublishablePackage,
} from "./release-packages.ts";
function writeManifest(root: string, path: string, manifest: Record<string, unknown>): void {
mkdirSync(join(root, path), { recursive: true });
writeFileSync(join(root, path, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
}
function fixture(): string {
const root = mkdtempSync(join(tmpdir(), "hf-release-packages-"));
writeFileSync(
join(root, "package.json"),
`${JSON.stringify({ private: true, workspaces: ["packages/*"] }, null, 2)}\n`,
);
for (const entry of PUBLISHABLE_PACKAGES) {
writeManifest(root, entry.workspacePath, { name: entry.workspaceName, version: "1.0.0" });
}
writeManifest(root, "packages/private-tool", {
name: "@hyperframes/private-tool",
version: "1.0.0",
private: true,
});
return root;
}
// One fixture-backed matrix documents the complete reconciliation contract.
// fallow-ignore-next-line unit-size
describe("publishable package roster", () => {
it("covers every public workspace exactly once and excludes private workspaces", () => {
const root = fixture();
try {
const discovered = discoverWorkspacePackages(root);
assert.equal(discovered.filter((entry) => !entry.private).length, 13);
assert.deepEqual(validatePublishablePackages(root), PUBLISHABLE_PACKAGES);
assert.equal(
PUBLISHABLE_PACKAGES.find((entry) => entry.workspaceName === "@hyperframes/cli")?.npmName,
"hyperframes",
);
assert.equal(
PUBLISHABLE_PACKAGES.find((entry) => entry.workspaceName === "@hyperframes/cli")
?.publishMode,
"manifest-name-override",
);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("mutation-pins a public workspace omitted from the roster", () => {
const root = fixture();
try {
const withoutSdk = PUBLISHABLE_PACKAGES.filter(
(entry) => entry.workspaceName !== "@hyperframes/sdk",
);
assert.throws(
() => validatePublishablePackages(root, withoutSdk),
/public workspace.*@hyperframes\/sdk.*missing/i,
);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("fails closed for duplicate paths, workspace names, and npm names", () => {
const root = fixture();
const first = PUBLISHABLE_PACKAGES[0]!;
try {
for (const duplicate of [
{ ...PUBLISHABLE_PACKAGES[1]!, workspacePath: first.workspacePath },
{ ...PUBLISHABLE_PACKAGES[1]!, workspaceName: first.workspaceName },
{ ...PUBLISHABLE_PACKAGES[1]!, npmName: first.npmName },
]) {
const roster: PublishablePackage[] = [first, duplicate];
assert.throws(() => validatePublishablePackages(root, roster), /duplicate/i);
}
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("rejects missing manifests, name mismatches, private entries, and invalid mappings", () => {
const root = fixture();
const first = PUBLISHABLE_PACKAGES[0]!;
try {
assert.throws(
() =>
validatePublishablePackages(root, [
{ ...first, workspacePath: "packages/does-not-exist" },
]),
/manifest.*does not exist/i,
);
const manifestPath = join(root, first.workspacePath, "package.json");
const original = readFileSync(manifestPath, "utf8");
writeFileSync(manifestPath, original.replace(first.workspaceName, "@hyperframes/wrong"));
assert.throws(() => validatePublishablePackages(root), /workspace name mismatch/i);
writeFileSync(manifestPath, original);
writeManifest(root, first.workspacePath, {
name: first.workspaceName,
version: "1.0.0",
private: true,
});
assert.throws(() => validatePublishablePackages(root), /private.*roster/i);
writeFileSync(manifestPath, original);
assert.throws(
() =>
validatePublishablePackages(root, [{ ...first, npmName: "renamed-without-override" }]),
/mapping.*manifest-name-override/i,
);
const invalidOverride: PublishablePackage = {
...first,
npmName: "renamed-core",
publishMode: "manifest-name-override",
};
assert.throws(
() =>
validatePublishablePackages(
root,
PUBLISHABLE_PACKAGES.map((entry) =>
entry.workspaceName === first.workspaceName ? invalidOverride : entry,
),
),
/only.*@hyperframes\/cli.*hyperframes/i,
);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
+174
View File
@@ -0,0 +1,174 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
export type PublishMode = "workspace" | "manifest-name-override";
export type PublishablePackage = {
workspacePath: string;
workspaceName: string;
npmName: string;
publishMode: PublishMode;
};
export type DiscoveredWorkspace = {
workspacePath: string;
workspaceName: string;
private: boolean;
};
function packageEntry(
workspacePath: string,
workspaceName: string,
npmName: string,
publishMode: PublishMode = "workspace",
): PublishablePackage {
return { workspacePath, workspaceName, npmName, publishMode };
}
/** Ordered release roster shared by versioning and npm publication. */
export const PUBLISHABLE_PACKAGES: readonly PublishablePackage[] = [
packageEntry("packages/parsers", "@hyperframes/parsers", "@hyperframes/parsers"),
packageEntry("packages/lint", "@hyperframes/lint", "@hyperframes/lint"),
packageEntry(
"packages/studio-server",
"@hyperframes/studio-server",
"@hyperframes/studio-server",
),
packageEntry("packages/core", "@hyperframes/core", "@hyperframes/core"),
packageEntry("packages/sdk", "@hyperframes/sdk", "@hyperframes/sdk"),
packageEntry("packages/engine", "@hyperframes/engine", "@hyperframes/engine"),
packageEntry("packages/player", "@hyperframes/player", "@hyperframes/player"),
packageEntry("packages/producer", "@hyperframes/producer", "@hyperframes/producer"),
packageEntry(
"packages/shader-transitions",
"@hyperframes/shader-transitions",
"@hyperframes/shader-transitions",
),
packageEntry("packages/studio", "@hyperframes/studio", "@hyperframes/studio"),
packageEntry("packages/aws-lambda", "@hyperframes/aws-lambda", "@hyperframes/aws-lambda"),
packageEntry(
"packages/gcp-cloud-run",
"@hyperframes/gcp-cloud-run",
"@hyperframes/gcp-cloud-run",
),
packageEntry("packages/cli", "@hyperframes/cli", "hyperframes", "manifest-name-override"),
];
type WorkspaceManifest = { name?: unknown; private?: unknown; workspaces?: unknown };
function readManifest(path: string): WorkspaceManifest {
const value: unknown = JSON.parse(readFileSync(path, "utf8"));
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`Package manifest ${path} must contain a JSON object.`);
}
return value;
}
// Fail-closed workspace-pattern validation is intentionally kept at discovery's single boundary.
// fallow-ignore-next-line complexity
function configuredWorkspaceDirectories(root: string): string[] {
const workspaces = readManifest(join(root, "package.json")).workspaces;
if (!Array.isArray(workspaces) || !workspaces.every((value) => typeof value === "string")) {
throw new Error("Root package.json must define an array of workspaces.");
}
const directories: string[] = [];
for (const pattern of workspaces) {
if (!pattern.endsWith("/*") || pattern.slice(0, -2).includes("*")) {
throw new Error(`Unsupported workspace pattern ${JSON.stringify(pattern)}.`);
}
const parent = pattern.slice(0, -2);
for (const entry of readdirSync(join(root, parent), { withFileTypes: true })) {
if (entry.isDirectory()) directories.push(join(parent, entry.name));
}
}
return directories.sort();
}
export function discoverWorkspacePackages(root: string): DiscoveredWorkspace[] {
return configuredWorkspaceDirectories(root).map((workspacePath) => {
const manifestPath = join(root, workspacePath, "package.json");
if (!existsSync(manifestPath))
throw new Error(`Workspace manifest does not exist: ${manifestPath}`);
const manifest = readManifest(manifestPath);
if (typeof manifest.name !== "string" || manifest.name.length === 0) {
throw new Error(`Workspace manifest ${manifestPath} has no package name.`);
}
return { workspacePath, workspaceName: manifest.name, private: manifest.private === true };
});
}
function rejectDuplicates(roster: readonly PublishablePackage[], key: keyof PublishablePackage) {
const seen = new Set<string>();
for (const entry of roster) {
const value = entry[key];
if (seen.has(value)) throw new Error(`Duplicate ${key} in publish roster: ${value}`);
seen.add(value);
}
}
// One reconciliation pass owns every roster invariant so consumers cannot validate subsets.
// fallow-ignore-next-line complexity
export function validatePublishablePackages(
root: string,
roster: readonly PublishablePackage[] = PUBLISHABLE_PACKAGES,
): readonly PublishablePackage[] {
rejectDuplicates(roster, "workspacePath");
rejectDuplicates(roster, "workspaceName");
rejectDuplicates(roster, "npmName");
const discovered = discoverWorkspacePackages(root);
const byPath = new Map(discovered.map((workspace) => [workspace.workspacePath, workspace]));
for (const entry of roster) {
const manifestPath = join(root, entry.workspacePath, "package.json");
if (!existsSync(manifestPath))
throw new Error(`Package manifest does not exist: ${manifestPath}`);
const workspace = byPath.get(entry.workspacePath);
if (!workspace)
throw new Error(`Roster path is not a configured workspace: ${entry.workspacePath}`);
if (workspace.workspaceName !== entry.workspaceName) {
throw new Error(
`Workspace name mismatch at ${entry.workspacePath}: expected ${entry.workspaceName}, found ${workspace.workspaceName}.`,
);
}
if (workspace.private)
throw new Error(`Private workspace cannot be a publish roster entry: ${entry.workspaceName}`);
if (entry.publishMode === "workspace" && entry.npmName !== entry.workspaceName) {
throw new Error(
`Package name mapping for ${entry.workspaceName} requires manifest-name-override mode.`,
);
}
if (entry.publishMode === "manifest-name-override" && entry.npmName === entry.workspaceName) {
throw new Error(
`manifest-name-override requires a distinct npm name for ${entry.workspaceName}.`,
);
}
if (
entry.publishMode === "manifest-name-override" &&
(entry.workspacePath !== "packages/cli" ||
entry.workspaceName !== "@hyperframes/cli" ||
entry.npmName !== "hyperframes")
) {
throw new Error(
"Only @hyperframes/cli may use manifest-name-override to publish as hyperframes.",
);
}
if (entry.publishMode !== "workspace" && entry.publishMode !== "manifest-name-override") {
throw new Error(`Invalid publish mode for ${entry.workspaceName}.`);
}
}
const rosterNames = new Set(roster.map((entry) => entry.workspaceName));
for (const workspace of discovered) {
if (!workspace.private && !rosterNames.has(workspace.workspaceName)) {
throw new Error(
`Public workspace ${workspace.workspaceName} is missing from the publish roster.`,
);
}
if (workspace.private && rosterNames.has(workspace.workspaceName)) {
throw new Error(
`Private workspace ${workspace.workspaceName} cannot be in the publish roster.`,
);
}
}
return roster;
}
+9 -20
View File
@@ -19,22 +19,7 @@ import { join } from "path";
import { execFileSync } from "child_process";
import { pathToFileURL } from "url";
import { CLI_SEMVER_PATTERN } from "./cli-options.ts";
const PACKAGES = [
"packages/parsers",
"packages/lint",
"packages/studio-server",
"packages/core",
"packages/engine",
"packages/player",
"packages/producer",
"packages/shader-transitions",
"packages/studio",
"packages/cli",
"packages/aws-lambda",
"packages/gcp-cloud-run",
"packages/sdk",
];
import { validatePublishablePackages } from "./release-packages.ts";
const PLUGINS = [".claude-plugin", ".codex-plugin", ".cursor-plugin"];
@@ -67,7 +52,7 @@ function main() {
updatePluginVersions(options.version);
console.log(
`\nSet ${PACKAGES.length} packages and ${PLUGINS.length} plugin manifests to v${options.version}`,
`\nSet ${publishablePackages().length} packages and ${PLUGINS.length} plugin manifests to v${options.version}`,
);
if (options.skipTag) {
@@ -102,8 +87,8 @@ export function parseReleaseOptions(args: string[]): ReleaseOptions {
}
function updatePackageVersions(version: string) {
for (const pkg of PACKAGES) {
const pkgPath = join(ROOT, pkg, "package.json");
for (const pkg of publishablePackages()) {
const pkgPath = join(ROOT, pkg.workspacePath, "package.json");
const content = JSON.parse(readFileSync(pkgPath, "utf-8"));
const oldVersion = content.version;
content.version = version;
@@ -310,13 +295,17 @@ export function docsChangelogEntryHasGeneratedTodo(content: string, marker: stri
export function releaseAllowedPaths(version: string) {
return [
...PACKAGES.map((pkg) => join(pkg, "package.json")),
...publishablePackages().map((pkg) => join(pkg.workspacePath, "package.json")),
...PLUGINS.map((plugin) => join(plugin, "plugin.json")),
"docs/changelog.mdx",
join("releases", `v${version}.md`),
];
}
function publishablePackages() {
return validatePublishablePackages(ROOT);
}
// Collect every uncommitted path (modified-tracked + untracked) as clean,
// repo-relative paths. We deliberately use `diff --name-only` and `ls-files`
// with `-z` rather than parsing `git status --porcelain`: the porcelain